Search code examples
phparraysmultidimensional-arrayparent-childdescendant

PHP - Apply operations to descendant arrays regardless of parent arrays


In a multidimensional array, I'm trying to select all descendant arrays with a certain key, no matter what their parent arrays are. I know the following syntax doesn't work, but hopefully it will help illustrate what I'm trying to accomplish:

<?php
  foreach ($array[*][*]['descendant'] as $descendent) {
     // do stuff
  }
?>

Similarly, I need to figure out whether sibling arrays do not contain this array key. Something like this (again, I know the syntax is horribly wrong):

<?php
  foreach ($array[*][*]['descendant'] < 1 as $descendent) {
     // do stuff
  }
?>

Solution

  • If there are always 3-dimensional array, you can use nested loop:

    foreach($array as $lv1) {
        foreach($lv1 as $lv2) {
            foreach($lv2['descendant'] as $descendent) {
                  // do stuff
            }
        }
    }
    

    If you want to support unlimited number of dimension, you can use this ugly code

    function drill($arr) {
        if (isset($arr) && is_array($arr)) {
            foreach($arr as $key => $value) {
                if ($key == 'descendant') {
                    foreach($value as $descendent) {
                        // do stuff here
                    }
                } else {
                    drill($value);
                }
            }
        }
    }
    drill($array);