-1

我正在尝试获取所有包含

['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,所以我想 foreachsaleaccess

4

3 回答 3

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;
    }
}
于 2013-09-15T07:46:52.117 回答
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";
}

相同的输出

于 2013-09-15T07:47:05.897 回答
1

简单地你可以尝试这样的事情来循环你的$array

foreach($array as $arr){
    if(isset($arr['tags']) && $arr['tags'] == "box"){
        // do more stuff
    }
}
于 2013-09-15T07:55:25.370 回答