如何解决如何通过PHP将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
}
解决方法
- 使数据成为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)));
,
您可以首先使用解码
$students = json_decode($json);
然后您可以遍历所有学生,
foreach($students as $key => $student)
现在您可以使用以下方式拆分该字符串
$studentAtributes = explode(',$student);
,然后使用遍历所有属性
foreach($studentAtributes as $attribute)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。