我有:
$all = array(
array('id'=>1, 'cat'=>'Main','type'=>'Name0'),
array('id'=>2, 'cat'=>'Main','type'=>'Name1'),
array('id'=>3, 'cat'=>'Main','type'=>'Name3'),
array('id'=>4, 'cat'=>'Main','type'=>'Name4'),
array('id'=>5, 'cat'=>'Secondary','type'=>'Name5'),
array('id'=>6, 'cat'=>'Secondary','type'=>'Name6'),
array('id'=>7, 'cat'=>'Secondary','type'=>'Name7'),
array('id'=>8, 'cat'=>'Other','type'=>'Name8'),
array('id'=>9, 'cat'=>'Other','type'=>'Name9'),
array('id'=>10, 'cat'=>'Other','type'=>'Name10'),
array('id'=>11, 'cat'=>'Other','type'=>'Name11'),
);
$result = array();
foreach($all as $array){
$result[$array['cat']][] = array('id'=>$array['id'],'type'=>$array['type']);
}
$json_type = json_encode($result);
返回:
{"Main":[{"id":"1","type":"name1"},{"id":"2","type":"name2"},{"id":"3","type":"name3"},{"id":"4","type":"name4"}],"Secondary":[{"id":"5","type":"name5"},{"id":"6","type":"name6"},{"id":"7","type":"name7"}],"Other":[{"id":"8","type":"name8"},{"id":"9","type":"name9"},{"id":"10","type":"name10"},{"id":"11","type":"name11"}]}
但我需要它返回为:
[
{
"text": "Main",
"children": [
{
"id": "1",
"text": "name1"
},
{
"id": "2",
"text": "name2"
},
{
"id": "3",
"text": "name3"
},
{
"id": "4",
"text": "name4"
}
]
},
{
"text": "Secondary",
"children": [
{
"id": "5",
"text": "name5"
},
{
"id": "6",
"text": "name6"
},
{
"id": "7",
"text": "name7"
}
]
},
{
"text": "Other",
"children": [
{
"id": "8",
"text": "name8"
},
{
"id": "9",
"text": "name9"
},
{
"id": "10",
"text": "name10"
},
{
"id": "11",
"text": "name11"
}
]
}
]
为了使用 select2 JQuery 插件,我正在使用。“孩子”的名字无关紧要,我认为这只是一个占位符,因此可以正确解析。我不知道我会怎么做,我一直在尝试str_replace()
,但即使这样也没有那么好。