我有一个表用户。 在这个表中,我有一个字段,在该字段中的数据类似于这个测试,test1,test2。我正在使用 ajax 从这个表中获取数据并将其显示在 php 文件中。
我能够获取数据,但由于 select2 插件。 我需要对此数据进行正确的格式化。
获取.php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
echo json_encode($data);
关键字字段的数据类似于这样test,test1,test2
我需要像这样以正确的 JSON 格式制作它。
id:test text:test
id:test1 text:test1
等等。
有没有可能让它像。
在
代码中添加此代码(新代码有注释):-
<?php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
// code need to add
$new_data = explode(',',$data['keywords']);
$final_data = array();
foreach($new_data as $new_dat){
$final_data[] = array('id'=>$new_dat,'text'=>$new_dat);
}
echo "<pre/>";print_r( $final_data);
$data['keywords'] = $final_data; // assingnment
// print json encoded data in last
echo json_encode($data);
?>
示例代码:- https://eval.in/528365
是的,您可以在空数组内制作二维数组,然后像这样$arrays = ('a' => 'b'),然后json_encode($arrays)现在你得到json对象
这是你要找的吗:
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
$data = array(
"id" => $data['keywords'],
"text" => $data['keywords']
);
}
echo json_encode($data);