首页 > 解决方案 > 如何通过PHP将一列json对象拆分为更多列

问题描述

如何拆分此 json 对象以发布到数据库名称、爱好、年龄的列

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

我的数据库名称:新,表名称:注册,这是我的 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
}

标签: phpmysqljsonrest

解决方案


  • 使数据成为 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)));

推荐阅读