gpt4 book ai didi

php - 将 php 数组映射到嵌套的 json

转载 作者:行者123 更新时间:2023-12-05 07:56:30 25 4
gpt4 key购买 nike

我一直在到处寻找提示,有一些问答看起来有点像这样,但到目前为止还没有运气。我基本上是在尝试获取这个 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);

如果您需要任何部分的解释,请告诉我...

关于php - 将 php 数组映射到嵌套的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28646439/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com