PHP:按字符串选择器查找数组元素

时间:2013-04-16 11:13:14

标签: php arrays search multidimensional-array

我试图理解使用“selector”在多维数组中找到元素的方法。

$vars = array(
    'site' => 'Stackoverflow',
    'menu' => array(
        'items' => array('Questions', 'Tags', 'Users', 'Badges', 'Unanswered'),
    ),
    'sidebar' => array(
        'tags' => array(
            'c_sharp' => 68,
            'java' => 62,
            'javascript' => 52,
            'jquery' => 50
        )
    )
);

我想要一些函数mixed find(string $selector, array $array)

用法

$site = find('site', $vars);
// result: "Stackoverflow"

$menuItems = find('menu.items', $vars);
// result: ["Questions", "Tags", "Users", "Badges", "Unanswered"]

$tags = find('sidebar.tags', $vars);
// result: ["c_sharp" => 68, "java" => 62, "javascript" => 52, "jquery" => 50]

$javascriptQuestionsCount = find('sidebar.tags.javascript', $vars);
// result: 52

$undefinedElement = find('footer.copyright.year', $vars);
// result: null

有谁能建议我实现这样的功能的方法,或者可能有一些现成的解决方案?

提前致谢。

2 个答案:

答案 0 :(得分:3)

Laravel有一个完成此功能的功能,它被称为array_get()

您可能希望忽略value()功能,但您可以return $default;代替。


/**
 * Get an item from an array using "dot" notation.
 *
 * <code>
 *      // Get the $array['user']['name'] value from the array
 *      $name = array_get($array, 'user.name');
 *
 *      // Return a default from if the specified item doesn't exist
 *      $name = array_get($array, 'user.name', 'Taylor');
 * </code>
 *
 * @param  array   $array
 * @param  string  $key
 * @param  mixed   $default
 * @return mixed
 */
function array_get($array, $key, $default = null)
{
    if (is_null($key)) return $array;

    // To retrieve the array item using dot syntax, we'll iterate through
    // each segment in the key and look for that value. If it exists, we
    // will return it, otherwise we will set the depth of the array and
    // look for the next segment.
    foreach (explode('.', $key) as $segment)
    {
        if ( ! is_array($array) or ! array_key_exists($segment, $array))
        {
            return value($default);
        }

        $array = $array[$segment];
    }

    return $array;
}

/**
 * Return the value of the given item.
 *
 * If the given item is a Closure the result of the Closure will be returned.
 *
 * @param  mixed  $value
 * @return mixed
 */
function value($value)
{
    return (is_callable($value) and ! is_string($value)) ? call_user_func($value) : $value;
}

答案 1 :(得分:0)

类似的东西:

   <?php
$vars = array(
    'site' => 'Stackoverflow',
    'menu' => array(
        'items' => array('Questions', 'Tags', 'Users', 'Badges', 'Unanswered'),
    ),
    'sidebar' => array(
        'tags' => array(
            'c_sharp' => 68,
            'java' => 62,
            'javascript' => 52,
            'jquery' => 50
        )
    )
);

function find ($key, $array){
  $keys = explode(".",$key);
    $currArr = $array;
    for ($i=0; $i<count($keys);$i++){
        if (isset($currArr[$keys[$i]])){
          $currArr = $currArr[$keys[$i]];
        }else{
          return null;
        }
    }

    return $currArr;
}

$site = find('site', $vars);
print_r($site);
echo "<br />";

$menuItems = find('menu.items', $vars);
print_r($menuItems);
echo "<br />";

$tags = find('sidebar.tags', $vars);
print_r($tags);
echo "<br />";

$javascriptQuestionsCount = find('sidebar.tags.javascript', $vars);
print_r($javascriptQuestionsCount);
echo "<br />";

$undefinedElement = find('footer.copyright.year', $vars);
print_r($undefinedElement);
echo "<br />";
?>

输出:

Stackoverflow
Array ( [0] => Questions [1] => Tags [2] => Users [3] => Badges [4] => Unanswered ) 
Array ( [c_sharp] => 68 [java] => 62 [javascript] => 52 [jquery] => 50 ) 
52
null

小提琴:

http://phpfiddle.org/lite/code/u7u-8jx

没有任何lib工作,只是简单的PHP。