php - 如何获取数组对应键的值

查看:271
本文介绍了php - 如何获取数组对应键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

已知一个多维数组 arr, 以及一个另一个数组 key = [1,2], 其中key中的第一个元素代表arr数组的第一个纬度, 第二个元素代表arr 的第二个纬度, 以此类推, key的元素个数不确定, 该如何获取arr 对应的key列出的所对应的值,
比如上面的key = 1, 2], 我就要获取arr[1, 如何key = 1,2,4], 我要获取arr[1[4]....

解决方案

<?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']);

这篇关于php - 如何获取数组对应键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆