0

I have a array $a and some key arrays e.g. $keys1, $keys2,....

$a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);

$keys1 = array('a','b','c');

$keys2 = array('a','b');

$a =  Array
    (
        [a] => Array
            (
                [b] => Array
                    (
                        [c] => Array
                            (
                                [d] => 123
                                [s] => 4
                            )

                        [r] => 3
                    )

                [q] => 2
            )

        [p] => 1
    )

whenever $keys1 is used, output should be

Array
(
    [d] => 123
    [s] => 4
)

or whenever $keys2 is used, output should be

Array
(
  [c] => Array
    (
        [d] => 123
        [s] => 4
    )
)

this is very simple I can achieve result by using $a[a][b][c] in first case and by using $a[a][b] in second case

Problem: these $keys are provided in form of array at run time, Is there any function in php to get the result?

2
  • Is something wrong with my answer then please say so. I'd be happy to fix it. Commented Sep 15, 2017 at 7:03
  • there is nothing wrong in your answer, actually I was searching for a bulid in php function Commented Sep 15, 2017 at 9:42

1 Answer 1

1

Try this.
Comments are in code.

It will loop through the keys and return the searched value.

$a = array('a'=>array('b'=>array('c'=>array('d'=>123,'s'=>4),'r'=>3),'q'=>2),'p'=>1);

$keys1 = array('a','b','c');

$keys2 = array('a','b');
$keys = $keys1; // set this as "search value"

$value = $a; // create a copy of original array. Maybe not needed?
Foreach($keys as $key){ // loop keys in search value
    $value = $value[$key]; // overwrite $value with subarray of $value[$key]
}

Var_dump($value); // dump the search return.

https://3v4l.org/ZHBMa

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.