如何在PHP中的多维数组中添加新的键和值字段



我有一个具有以下格式的数组。示例Json供参考:https://jsoneditoronline.org/#left=cloud.42c7485653ea40549da90cf4338f8b23

我想添加";super_parent_ id";在每个childData数组中。因此,如果childData存在,我需要将super_parent_id附加到该子数组中。类似地,如果该数组中存在childData数组,我需要将super_parent_id附加到该子数组中。

我认为递归可以解决这个问题,但我不确定如何做到。非常感谢。

是的,正确,递归是解决这个问题的方法之一。下面是一个代码片段,解释如何实现这种数据结构的递归修改。

function appendSuperParentId(&$elem, $superParentId){
$elem["super_parent_id"] = $superParentId;
if (isset($elem["childData"])){
appendSuperParentId($elem["childData"], $superParentId);
}
}
$elems = [
[
"name" => "xyz",
"childData" => [
"name" => "foo",
"childData" => [
] 
]
]
];
for ($i = 0; i < count($elems); $i++){
appendSuperParentId($elems[$i]["childData"], $superParentId);
}

并没有经过测试,但这个想法应该可行。

我有一个使用foreach:的更清洁的解决方案

<?php
$data = array (
'data' => 
array (
'valueId' => '21803826062',
'hasChildren' => true,
'parentId' => '21768700190',
'name' => 'Test Unit 002',
'childData' => 
array (
21810803918 => 
array (
'valueId' => '21810803918',
'hasChildren' => false,
'parentId' => '21803826062',
'name' => 'Test Unit 003',
'childData' => NULL,
'adUnitCode' => 'Test_unit_003',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
21810890245 => 
array (
'valueId' => '21810890245',
'hasChildren' => false,
'parentId' => '21803826062',
'name' => 'Test Unit 002_1',
'childData' => NULL,
'adUnitCode' => 'test_unit_002_1',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
),
'adUnitCode' => 'unit002',
'adUnitSizes' => NULL,
'adType' => 'TEXT_AND_IMAGE',
'smartSizeMode' => 'NONE',
),
);
$parentId = $data['data']['parentId'];
foreach($data['data']['childData'] as $key => $value){
$data['data']['childData'][$key]['super_parent_id'] = $parentId;
}
print_r($data);

PHP沙盒链接

最新更新