1

I've here two multi-dimensional arrays.

How would you do to get the image_to_get value in the $b array thanks to the $a array ?

$a = array(
    'thumbs' => array(
        '0' => array(
            'thumb1a' => array(
                '0' => array(
                    'thumb1' => ""
                )
            )
        )
    )
);

$b = array(
    'thumbs' => array(
        '0' => array(
            'thumb1a' => array(
                '0' => array(
                    'thumb1' => "image_to_get"
                )
            ),
            'thumb2' => 'image2',
            'thumb3' => 'image3',
            'thumb4' => 'image4',
            'thumb5' => 'image5',
        )
    )
);
3
  • Is it always at a known depth, or do you have handle any level of nesting? Commented Jan 23, 2014 at 8:22
  • No it's not always at a known depth. Commented Jan 23, 2014 at 8:31
  • stackoverflow.com/questions/19299137/… Can you check this question? It seems related to yours Commented Jan 23, 2014 at 8:33

1 Answer 1

0

You can try with:

function getAPath($array) {
    if (empty($array)) {
        return array();
    }
    $key = key($array);

    return array_merge(array($key), getAPath($array[$key]));
}
function getBValue($array, $path) {
    $key = array_shift($path);

    if (is_null($key) || empty($array)) {
        return $array;
    }

    return getBValue($array[$key], $path);
}

$aPath  = getAPath($a);
$bValue = getBValue($b, $aPath);
var_dump($bValue);

First function getAPath flatterns your $a array into:

array (size=5)
  0 => string 'thumbs' (length=6)
  1 => int 0
  2 => string 'thumb1a' (length=7)
  3 => int 0
  4 => string 'thumb1' (length=6)

Second function getBValue walks through the $b array using $aPath.

Below lovely one-liners ;-)

function getAPath($array) {
    return empty($array) ? array() : array_merge(array($key = key($array)), getAPath($array[$key]));
}
function getBValue($array, $path) {
    return (is_null($key = array_shift($path)) || empty($array)) ? $array :  getBValue($array[$key], $path);
}
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.