Home >Backend Development >PHP Tutorial >How to get the value of the corresponding key in an array
We know a multi-dimensional array arr, and another array key = [1,2], where the first element in key represents the first latitude of arr array, and the second element represents the second dimension of arr Latitude, and so on, the number of elements of key is uncertain, how to get the corresponding value listed in the key corresponding to arr,
For example, the above key = 1, 2], I need to get arr[1, How to key = 1,2,4], I want to get arr[1[4]....
We know a multi-dimensional array arr, and another array key = [1,2], where the first element in key represents the first latitude of arr array, and the second element represents the second dimension of arr Latitude, and so on, the number of elements of key is uncertain, how to get the corresponding value listed in the key corresponding to arr,
For example, the above key = 1, 2], I need to get arr[1, How to key = 1,2,4], I want to get arr[1[4]....
<code class="php"><?php $arr = [ [ "value" => "0", "children" => [ [ "value" => "0-0", ], [ "value" => "0-1", "children" => [ [ "value" => "0-1-0", ], ] ], ] ], [ "value" => "1", "children" => [ [ "value" => "1-0", "children" => [ [ "value" => "1-0-0", "children" => [ [ "value" => "1-0-0-0", "children" => [] ], ] ], ] ], ] ] ]; $key = [0, 1]; function getValueByKey($arr, $key) { $index = array_shift($key); if(count($key) === 0) return $arr[$index]; return getValueByKey($arr[$index]['children'], $key); } // 更改對應索引的 value function setValueByKey(&$arr, $key, $value) { $index = array_shift($key); if(count($key) === 0) return $arr[$index]['value'] = $value; return setValueByKey($arr[$index]['children'], $key, $value); } setValueByKey($arr, $key, '123'); // 返回匹配到的數組,再看要取出啥,這邊 value 為例 print_r(getValueByKey($arr, $key)['value']); </code>