我正在尝试获取包含
的所有数组['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
)
)
此数组中的 sale
和access
有[tags] => box
,因此我想预先sale
和access
答案 0 :(得分:1)
$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;
}
}
答案 1 :(得分:1)
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
或者,您也可以使用continue
foreach ($array as $k => $v) {
if (!array_key_exists("tags", $v) || $v["tags"] !== "box") {
continue;
}
echo $k, " ", $v["url"], "\n";
}
相同的输出
答案 2 :(得分:1)
您只需尝试使用此类内容循环$array
foreach($array as $arr){
if(isset($arr['tags']) && $arr['tags'] == "box"){
// do more stuff
}
}