Dynamically accessing multidimensional array value

前端 未结 4 1621
长发绾君心
长发绾君心 2021-01-13 21:50

I\'m trying to find (or create) a function. I have a multidimensional array:

$data_arr = [
    \"a\" => [
        \"aa\" => \"abfoo\",
        \"ab\"          


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 22:18

    You need a function like this:

    function getValue($data_arr, $data_arr_call) {
        foreach ($data_arr_call as $index) {
            if (isset($data_arr[$index])) {
                $data_arr = $data_arr[$index];
            } else {
                return false;
            }
        }
        return $data_arr;
    }
    

    And use it like this:

    $data_arr = [
        "a" => [
            "ab" => [
                "abc" => "abbfoo",
            ],
        ],
    ];
    $data_arr_call = ["a", "ab", "abc"];
    $value = getValue($data_arr, $data_arr_call);
    if ($value) {
        // do your stuff
    }
    

提交回复
热议问题