Search code examples
phparraysarray-column

array_column doesn't work with first key in nested array


I have a nested array like so

$array = array(
  [2] => array(
      [5] => array(
          [7] => array(
               [46] => array()
          )
      ),
      [108] => array()
  ), 
  [14] => array(),
  [8] => array(
      [72] => array()
  )
)

With only knowing the key, I need to find it in the array and get all it's nested data. Using array_column only works if I start with a second level key

$foo = array_column($array, 2) // returns empty array
$bar = array_column($array, 5) // returns all its nested data

Why is that and what's the correct way to do this with any key without knowing the level


Solution

  • This is a recursive function which at each point checks if the key matches the required one, if so it returns the value, if not it will look in elements which are also arrays (which is where the recursive bit comes in) and return if a match is found there...

    function nested_array_key_search ( array $array, $key ) {
        foreach ( $array as $elementKey => $element )  {
            if ( $elementKey === $key ) {
                return $element;
            }
            if ( is_array($element) )   {
                $nested = nested_array_column ( $element, $key );
                // If the recursive call returns a value
                if ( $nested !== false )    {
                    return $nested;
                }
            }
        }
        // Not found, return false
        return false;
    }
    $bar = nested_array_key_search($array, 2);
    
    print_r($bar);
    

    gives...

    Array
    (
        [5] => Array
            (
                [7] => Array
                    (
                        [46] => Array
                            (
                            )
    
                    )
    
            )
    
        [108] => Array
            (
            )
    
    )