Home > Backend Development > PHP Tutorial > How to get the value of the corresponding key in an array

How to get the value of the corresponding key in an array

WBOY
Release: 2016-07-06 13:52:26
Original
1546 people have browsed it

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]....

Reply content:

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>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template