我有一个像这样的N级多维数组:
Array
(
[0] => Array
(
[id] => 7_cat
[text] => cat1
[children] => Array
(
[0] => Array
(
[id] => 9_cat
[text] => cat3
)
)
)
[1] => Array
(
[id] => 8_cat
[text] => cat2
)
[2] => Array
(
[id] => 13_cat
[text] => cat4
)
)
我有一个这样的索引数组:
Array
(
[0] => 0
[1] => children
[2] => 0
[3] => id
)
所以我想在这些深度的第一个数组中添加一个新元素。 在这个例子中,我想在$firstarray[0]['children'][0]['id']中添加一个新元素。我该怎么做?
多谢
像这样做
这里$oldArray是您的第一个阵列
$indexArray=Array
(
[0] => 0
[1] => children
[2] => 0
[3] => id
);
$indexForold=[];
foreach($indexArray as $indx){
$indexForold=$indexForold[$indx];
}
$oldArray[$indexForold]=$myVal;
解决方案是,在遍历数组时使用引用来保留对当前数组元素的引用。
- 这里
$nArr
是你的n维数组,$indexArr
是你的索引数组。 - 并且不要忘记将
<YOUR_VALUE>
替换为所需的值。
所以你的代码应该是这样的:
$arrLength = count($indexArr);
$tmpArr = null;
$i = 0;
for(; $i < $arrLength - 1; ++$i){
if($tmpArr == null){
$tmpArr = &$nArr[$indexArr[$i]];
}else{
$tmpArr = &$tmpArr[$indexArr[$i]];
}
}
$tmpArr[$indexArr[$i]] = <YOUR_VALUE>;
// now display the n-dimensional array
echo "<pre>";
print_r($nArr);
echo "</pre>";
你可以尝试这样的事情...
$array = [
[
'id' => '7_cat',
'text' => 'cat1',
'children' => [
[
'id' => '9_cat',
'text' => 'cat3'
]
]
],
[
'id' => '8_cat',
'text' => 'cat2'
],
[
'id' => '13_cat',
'text' => 'cat4'
]
];
$multIndexValue = function (array $indexList, array $searchArray) {
$result = $searchArray;
foreach ($indexList as $index) {
$result = $result[$index];
}
return $result;
};
$search = [0, 'children', 0, 'id'];
$result = $multIndexValue($search, $array); // string(5) "9_cat"