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_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 = 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

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