mysql - How to split a Column of json Object to More Column via PHP

how can i split this json object to post to column in database name, hobby, age
{
"student1":"john smitch,reading,15",
"student2":"albert North, running,13"
}
My db Name: new, Table Name: registration, This is my php code:
public function index_post()
{
//$this->some_model->update_user( ... );
$data = [
'name' => $this->post('student1'),
];
$message = ['registration was successful']
$this->db->insert("registration", $data);
$this->set_response($message, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
Answer
Solution:
- make the data an PHP array or object
- walk thru and trim the entries separated by comma
- insert row
$json = '{
"student1":"john smitch,reading,15",
"student2":"albert North, running,13"
}';
$sth = $db->prepare('INSERT INTO registration SET name=?, hobby=?, age=?');
foreach(json_decode($json) as $key => $value)
$sth->execute(array_map(fn($e) => trim($e), explode(',', $value)));
Answer
Solution:
You can first decode the JSON with
$students = json_decode($json);
then you can iterate through all students by
foreach($students as $key => $student)
now you can split this string with
$studentAtributes = explode(',', $student);
and then iterate over all attributes with
foreach($studentAtributes as $attribute)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: method illuminate\database\eloquent\collection::paginate does not exist.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.