0

I am having a bit of trouble trying to explain this correctly, so please bear with me...

I need to be able to recursively select keys based on a given array. I can do this via a fairly simple foreach statement (as shown below). However, I prefer to do things via PHP's built in functions whenever possible.

$selectors = array('plants', 'fruits', 'apple');
$list = array(
    'plants' => array(
        'fruits' => array(
            'apple' => 'sweet',
            'orange' => 'sweet',
            'pear' => 'tart'
        )
    )
);

$select = $list;
foreach ($selectors as $selector) {
    if (isset($select[$selector])) {
        $select = $select[$selector];
    } else {
        exit("Error: '$selector' not found");
    }
}

echo $select;

See this code in action

My Question: Is there a PHP function to recursively select array keys? If there is not, is there a better way than in the example above?

Nicholas Summers
  • 4,444
  • 4
  • 19
  • 35
  • [The top comment](http://php.net/manual/en/function.array-search.php#91365) in the `array_search()` manual has a recursive function example – scrowler Dec 21 '14 at 19:55
  • @scrowler If I am reading it correctly, that function seems to search array values, whereas I need something to select known keys. – Nicholas Summers Dec 21 '14 at 19:58
  • Hey @NickJ, fair enough - there's a few other posts on StackOverflow and around that will help you look for the keys. Here's one: http://stackoverflow.com/a/2948985/2812842 – scrowler Dec 21 '14 at 20:00
  • @scrowler While that would be fine for strings, in the actual implementation the values will all be instances of a single class (each with unique properties). The real problem is that the value I am trying to retrieve could be 2 levels deep or just as easily 20 levels deep. – Nicholas Summers Dec 21 '14 at 21:06

1 Answers1

0

If i understand , you are searching about : http://php.net/recursivearrayiterator and http://php.net/recursiveiteratoriterator

And code something like that:

$my_itera = new RecursiveIteratorIterator(new RecursiveArrayIterator($my_array));

$my_keys = array();

foreach ($my_itera as $my_key => $value) {


    for ($i = $my_itera->getDepth() - 1; $i >= 0; $i--) {
        $my_key = $my_itera->getSubIterator($i)->key() . '_' . $my_key;
    }
    $my_keys[] = $my_key;
}
var_export($my_keys);

I Hope it works.

EngineerCoder
  • 1,445
  • 15
  • 30