Как разделить столбец объекта json на несколько столбцов с помощью PHP

#php #mysql #json #rest

#php #mysql #json #остальное

Вопрос:

как я могу разделить этот объект json для публикации в столбце имя базы данных, хобби, возраст

 {
"student1":"john smitch,reading,15",
"student2":"albert North, running,13"
}
  

Имя моей базы данных: new, Имя таблицы: registration, это мой php-код:

  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
}
  

Ответ №1:

  • сделайте данные PHP массивом или объектом
  • пройдите и обрежьте записи, разделенные запятой
  • вставить строку
 $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)));
  

Ответ №2:

Вы можете сначала декодировать JSON с помощью

 $students = json_decode($json);
  

затем вы можете выполнить итерацию по всем учащимся с помощью

 foreach($students as $key => $student)
  

теперь вы можете разделить эту строку с

 $studentAtributes = explode(',', $student);
  

а затем выполнить итерацию по всем атрибутам с

 foreach($studentAtributes as $attribute)