php - 如何通过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
}
解决方案
- 使数据成为 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)));
推荐阅读
- gcc - x86 中哪些 MOV 指令未使用或使用最少,可用于自定义 MOV 扩展
- asp.net-core - 无法连接到 Blazor webassembly 中的 SignalR
- python - 使用 assert_has_calls 方法获取在模拟断言中失败的实际调用
- django - djnago urls 文件中的路径设置困难
- c - 通过寄存器打开 Nucleo 64 F103RB 中的 LED
- wpf - 将 Combobox ItemsSource BindingContext 设置为 ViewModel
- c++ - 如何为向量编写 if 和 else 语句?
- python - 数据框字典中的圆形列
- xamarin.forms - 如何保存当前位置?
- c++ - 如何在 C++ 中关闭输入流?