0

Lets say I have an array like this:

$a = array(
    "foo",
    "bar"
);

and

$b = array(
    "foo" => array(
        "bar" => 1
    )
);

and I want to use $a to get $b[$a[0]][$a[1]]

Assumptions are 1..* length of $a and 1..* levels in $b.

4
  • Please share what you have tried. Commented Jan 5, 2015 at 19:22
  • 1
    ... and what you are attempting to obtain. Why does not $b[$a[0]][$a[1]] work for you? Commented Jan 5, 2015 at 19:23
  • @Eineki he wants a solution that works for any level of nesting Commented Jan 5, 2015 at 19:27
  • @Barmar I guessed the scope a couple of minutes after the comment posting (it still a poorly expressed question to me). I was working on the topics but you came out with a nice solution (I would just embrace the code into a try...catch to manage missing index) Commented Jan 5, 2015 at 19:37

2 Answers 2

2
$result = $b;
foreach ($a as $index) {
    $result = $result[$index];
}
echo $result;
Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't work at all! Because at the second iteration it's: $b["bar"], which don't exists!
1

This should work for you:

<?php

    //As an example
    $a = array(
        "foo",
        "bar",
        "xy",
        "ab"
    );

    $b = array(
        "foo" => array(
            "bar" => array(
                "xy" => array(
                    "ab" => 14  
                ),
            ),
        )
    );

    $end = $b;
    foreach ($a as $index)
        $end = $end[$index];

    echo $end;

?>

Output:

14

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.