我一直在搜索SO以获得提示,并且有一些q& a看起来有点像这样,但到目前为止还没有运气。 我基本上试图得到这个PHP数组:
array (size=xx)
14 =>
array (size=2)
0 => string '14' (length=2)
1 => float 80
15 =>
array (size=2)
0 => string '15' (length=2)
1 => float 70
1522 =>
array (size=4)
0 => string '15' (length=2)
1 => float 70
2 => string '22' (length=2)
3 => float 60
1523 =>
array (size=4)
0 => string '15' (length=2)
1 => float 70
2 => string '23' (length=2)
3 => float 70
152329 =>
array (size=6)
0 => string '15' (length=2)
1 => float 70
2 => string '23' (length=2)
3 => float 70
4 => string '29' (length=2)
5 => float 30
152334 =>
array (size=6)
0 => string '15' (length=2)
1 => float 70
2 => string '23' (length=2)
3 => float 70
4 => string '34' (length=2)
5 => float 80
16 =>
array (size=2)
0 => string '16' (length=2)
1 => float 30
1624 =>
array (size=4)
0 => string '16' (length=2)
1 => float 30
2 => string '24' (length=2)
3 => float 35
转换(或映射?)到这个json:
{
"children": [
{
"id": "14",
"name": "Id 14",
"value": "80.0",
"children": []
},
{
"id": "15",
"name": "ID 15",
"value": "70.0",
"children": [
{
"id": "22",
"name": "ID 22",
"score": "60.0",
"children": []
},
{
"id": "23",
"name": "Id 23",
"score": "70.0",
"children": [
{
"id": "29",
"name": "ID 29",
"score": "30.0",
"children": []
},
{
"id": "34",
"name": "Id 34",
"score": "80.0",
"children": []
}
]
}
]
},
{
"id": "16",
"name": "ID 16",
"score": "30.0",
"children": [
{
"id": "24",
"name": "ID 24",
"score": "35.0",
"children": []
}
]
}
]
}
我曾尝试使用php map()函数,但我无法正确转换。 那么,请你发一个片段或指向正确的方向吗?
答案 0 :(得分:0)
这应该可以解决问题。我假设您当前的数组名为$oldArray
// will use this later
function reindex($array) {
if (!empty($array['children'])) {
$array['children'] = array_values($array['children']);
foreach ($array['children'] as $key => $value) {
$array['children'][$key] = reindex($value);
}
}
return $array;
}
$newArray = array(
'children' => array()
);
// refactor array into something more suitable
foreach ($oldArray as $oldArrayKey => $oldArrayValues) {
$count = count($oldArrayValues);
$currentArray = &$newArray['children'];
for ($i = 0; $i < $count; $i = $i + 2) {
$id = $oldArrayValues[$i];
$value = $oldArrayValues[$i + 1];
if (!isset($currentArray[$id])) {
$currentArray[$id] = array(
'id' => $id,
'name' => 'ID ' . $id,
'value' => $value,
'children' => array()
);
}
$currentArray = &$currentArray[$id]['children'];
}
}
// reindex the children, or json_encode will treat ['children'] as an object instead of an array
$newArray = reindex($newArray);
echo json_encode($newArray);
如果您需要任何部分的解释,请告诉我......