我有一个JSON,我想从中映射键并生成另一个JSON。在order_data中,我要打印所有子表数据,然后最后要放父表数据
以下是我从中生成JSON的函数
public function example(){
$data = '{"details":[{"price":"4","selectedSubOptionsIds":[],"dis":"27025"},{"price":"1","selectedSubOptionsIds":[63138, 63137],"dis":"27027"}],"a":"1238","b":"2","c":"0","d":"NULL"}';
$data = json_decode($data);
$pz['a'] = $data->a;
$pz['b'] = $data->b;
$pz['c'] = $data->c;
$pz['d'] = $data->d;
$detailing = $data->details; //this is an array
$j=0;
foreach ($detailing as $value) {
$subOptIds = $value->selectedSubOptionsIds; //this is an array
$dis = $this->db->from('parent')->where('id',$value->dis)->get()->row();
$i=0;
if(count($subOptIds) <= 0){
$detail[$i]['a'] = $dis->name;
$detail[$i]['b'] = $dis->id;
$detail[$i]['c'] = $dis->price;
$i++;
}
else{
foreach ($subOptIds as $suboptid) {
$subopt = $this->db->from('child')->where('id',$suboptid)->get()->row();
$detail[$i]['a'] = $subopt->name;
$detail[$i]['b'] = $subopt->id;
$detail[$i]['c'] = $subopt->price;
$i++;
}
}
$j++;
}
$pz['order_data'] = $detail;
echo json_encode($pz);
}
它向我返回json:
{
"a": "1238",
"b": "2",
"c": "0",
"d": "NULL",
"order_data": Array[2][
{
"0": {
"a": "Test Dish 1",
"b": "27025",
"c": "100.0"
},
"a": "Pepsi",
"b": "63138",
"c": "40.0"
},
{
"a": "Cream",
"b": "63137",
"c": "25.0"
}
]
}
但是我希望order_data数组成为单个数组,并且它仅应包含对象,并且不应包含任何嵌套数组,就像下面的
{
"a": "1238",
"b": "2",
"c": "0",
"d": "NULL",
"order_data": Array[2][
{
"a": "Test Dish 1",
"b": "27025",
"c": "100.0"
},
{
"a": "Pepsi",
"b": "63138",
"c": "40.0"
},
{
"a": "Cream",
"b": "63137",
"c": "25.0"
}
]
}
答案 0 :(得分:1)
首先,据我所知,所显示的代码不可能产生您在问题中声明的输出-请参见https://eval.in/1032176上的演示
第二,不考虑上述内容,要获得您真正想要的输出,您只需解决一个小错误。将$i=0;
移动到外部foreach
外部-当前,每次循环浏览$detailing
中的每个项目时,它都会重置,因此{ {1}}数组在后续循环中被覆盖。您也完全不需要0
,它在任何地方都不会使用。
摘要:
$details
在https://eval.in/1032185上查看工作演示