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?

4
  • The top comment in the array_search() manual has a recursive function example Commented Dec 21, 2014 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. Commented Dec 21, 2014 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: stackoverflow.com/a/2948985/2812842 Commented Dec 21, 2014 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. Commented Dec 21, 2014 at 21:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.