How can I use a php array as a path to target a value in another array?

后端 未结 3 1506
你的背包
你的背包 2020-12-21 03:49

I want to access a specific array\'s property by using a separate array as the path. The problem is the property in question may be at any depth. Here\'s an example...

相关标签:
3条回答
  • 2020-12-21 04:11

    Here is a different approach:

    while($d = array_shift($path))
        $data = $data[$d];
    
    0 讨论(0)
  • 2020-12-21 04:12

    A simple loop should work:

    Update: sorry did check my code

    foreach($path as $id) 
    {
        $data = $data[$id];
    }
    
    echo $data;
    

    Result:

    deeper_value
    

    This will overwrite the $data array so you might want to make a copy of $data first like David did in his example.

    0 讨论(0)
  • 2020-12-21 04:13

    It's not the greatest code, but should work:

    function getValue($pathArray, $data)
    {
       $p = $data;
       foreach ($pathArray as $i)
       {
         $p = $p[$i];
       }
    
       return $p;
    }
    
    0 讨论(0)
提交回复
热议问题