我一直在SO中寻找提示,并且有一些类似的问答,但到目前为止还没有运气。我基本上是想得到这个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()函数,但是无法正确进行转换。因此,请您发布一个摘要或为我指明正确的方向?
这应该可以解决问题。我假设您当前的数组称为$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);
让我知道您是否需要任何解释...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句