当前位置: 动力学知识库 > 问答 > 编程问答 >

php - how to get multi-dimensional array data with another one-dimension array

问题描述:

What I'd like to do is have a function that accepts two arguments, both arrays, the first being a one-dimensional array of varying lengths and the second is a multi-dimensional array of varying depths and lengths. The first array is never associative, the second is always a fully associative array.

This function would return the requested value from the multi-dimensional array as indicated by the first array.

Assume that the first array will always be hand-written and passed to this function. Meaning the developer always knows there is a value to be returned from the multi-dimensional array and would never pass a request to the function where a value did not exist.

I think the code below is the best example at what I'm trying to achieve.

//Example multi-dimensional array

$multi = array(

'fruit' => array(

'red' => array(

'strawberries' => '$2.99/lb',

'apples' => '$1.99/lb'

),

'green' => array(

'honeydew' => '$3.39/lb',

'limes' => '$0.75/lb'

)

),

'vegetables' => array(

'yellow' => array(

'squash' => '$1.29/lb',

'bellpepper' => '$0.99/lb'

),

'purple' => array(

'eggplant' => '$2.39/lb'

)

),

'weeklypromo' => '15% off',

'subscribers' => array(

'[email protected]' => 'User 1',

'[email protected]' => 'User 2',

'[email protected]' => 'User 3',

'[email protected]' => 'User 4'

)

);

//Example one-dimensional array

$single = array('fruit', 'red', 'apples');

function magicfunc($single, $multi) {

//some magic here that looks something like below

$magic_value = $multi[$single[0]][$single[1]][$single[2]];

return $magic_value;

}

//Examples:

print magicfunc(array('fruit', 'red', 'apples'), $multi);

Output:

$1.99/lb

print magicfunc(array('subscribers', '[email protected]'), $multi);

Output:

User 3

print magicfunc(array('weeklypromo'), $multi);

Output:

15% off

网友答案:

This returns the values as requested:

function magicfunc($single, $multi) {
    while (true) {
        if (!$single) {
            break;
        }
        $searchIndex = array_shift($single);

        foreach ($multi as $k => $val) {
            if ($k == $searchIndex) {
                $multi = $val;
                continue 2;
            }
        }
    }
    return $multi;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: