按键分支搜索数组

时间:2014-10-28 22:31:13

标签: php arrays

我有一个如下所示的数组:

$array = array (
    [level_1] => array (
        [level_2] => array (
            [level_3] => something
        )
    ),
    [level_12] => array (
        [level_2] => somethingelse
    ),
    [level_13] => array (
        [level_22] => array (
            [level_3] => something
        )
    ),
);

键或值并不总是唯一的,但分支是。
我有一个看起来像这样的字符串:

$string = 'level_1-level_2-level_3';

这些是分支的关键。

我需要以某种方式根据该字符串从数组中获取值? 像这样:

$string_array = explode('-', $string);
$array[$string_array[0]][$string_array[1]][$string_array[2]] // something

但由于深度可能不同,这不是一个可行的解决方案......

3 个答案:

答案 0 :(得分:1)

试试这个简单的例子,不需要递归函数:

function get_item( $path, $array ) 
{
    $paths = explode( '-', $path );

    $result = $array;       
    foreach ( $paths as $path) {
        isset( $result[$path] ) ? $result = $result[$path] : $result = false;
    }

    return $result; 
}

$path = 'level_1-level_2-level_3';
echo get_item( $path, $array );

答案 1 :(得分:1)

试试这个:

    $array = array (
    'level_1' => array (
        'level_2' => array (
            'level_3' => 'something'
        )
    ),
    'level_12' => array (
        'level_2' => 'somethingelse'
    ),
    'level_13' => array (
        'level_22' => array (
            'level_3' => 'something'
        )
    ),
);
$string = 'level_1-level_2-level_3';
$keys = explode('-', $string);

echo getItemIterative($keys, $array);
echo "\n";
echo getItemRecursive($keys, $array);


function getItemIterative($keys, $array)
{
    $value = null;
    foreach ($keys as $key) {
        if ($value == null) {
            $value = $array[$key];
        }
        if (is_array($value) && array_key_exists($key, $value)) {
            $value = $value[$key];
        }
    }
    return $value;
}

function getItemRecursive($keys, $array)
{
    $key = array_shift($keys);
    $value = $array[$key];
    if (empty($keys)) {
        return $value;
    } else {
        return getItemRecursive($keys, $value);
    }
}

答案 2 :(得分:0)

制作一个$result变量,该变量最初指向数组的根,然后遍历您正在寻找的叶子上$string_array'到$result点的等级。< / p>

// stuff you already have:

$array = array(...); // your big array
$string = 'level_1-level_2-level_3';
$string_array = explode('-', $string);

// new stuff:

$result = $array;
foreach ($string_array as $level) {
    $result = $result[$level];
}

echo $result; // 'something'

工作示例:Ideone