繁体   English   中英

PHP-如果它们包含键=值,则获取数组

[英]PHP - get array if they contain a key=value

我正在尝试获取包含一个数组的所有数组

['tags'] => 'box'

这是我的数组:

array(
    [sale] => Array(
        [url] => ../users
        [label] => Users
        [tags] => box
    )   
    [history] => Array(
        [url] => ../history
        [label] => History
    )   
    [access] => Array(
        [url] => ../history
        [label] => Access
        [tags] => box
    )
)

在此数组中, saleaccess具有[tags] => box ,因此我想分别进行saleaccess

$array = array(...); // contains your array structure
$matches = array();  // stick the matches in here

foreach ($array as $key => $arr)
{
    if ( ! empty($arr['tags']) && $arr['tags'] === 'box')
    {
        // the array contains tag => box so stick it in the matches array
        $matches[$key] = $arr;
    }
}

array_filter应该工作

array_filter($array, function($sub) {
  return array_key_exists("tags", $sub) && $sub["tags"] === "box";
});

需要PHP >= 5.3


这是一个完整的例子

$filter = function($sub) {
  return array_key_exists("tags", $sub) && $sub["tags"] === "box";
};

foreach (array_filter($array, $filter) as $k => $v) {
  echo $k, " ", $v["url"], "\n";
}

输出量

sale ../users
access ../history

另外,您也可以使用继续

foreach ($array as $k => $v) {
  if (!array_key_exists("tags", $v) || $v["tags"] !== "box") {
    continue;
  }

  echo $k, " ", $v["url"], "\n";
}

相同的输出

只需您可以尝试使用类似方法来循环$array

foreach($array as $arr){
    if(isset($arr['tags']) && $arr['tags'] == "box"){
        // do more stuff
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM