[英]Search multidimensional array php
我有以下多維數組。
$arr = array(
0 => array(
'id' => 1,
'title' => 'title1',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb1',
'custodian' => 'custodia1',
'tags' => 'tag1',
'active' => 'Y',
),
1 => array(
'id' => '2',
'title' => 'title2',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb2',
'custodian' => 'custodia2',
'tags' => 'tag1,tag2',
'active' => 'Y',
),
2 => array(
'id' => '3',
'title' => 'title3',
'url' => 'http://www.foo.bar/',
'blurb' => 'blurb3',
'custodian' => 'custodia3',
'tags' => 'tag1,tag2,tag3',
'active' => 'Y',
),
);
我需要過濾數組,以便僅顯示標簽值中帶有“ tag2”的數組。
我看過array_filter
但array_filter
。
這是我的嘗試,但是根本不起作用。 不知道我在做什么錯。
$filterArr = array_filter($arr, function($tag) {
return ($tag['tags'] == 'tag2');
});
最簡單的方法是使用foreach循環,並在循環體內檢查“ tag2”
如果您需要刪除標記中沒有tag2的所有行,則可以使用下一個循環:
foreach ($arr as $key => $value) {
if (!preg_match('/\btag2\b/',$value['tags'])) {
unset($arr[$key]);
}
}
array_filter接受數組的每個元素並將其傳遞給指定的函數,在該函數中,您需要返回true或false,如果應保留則返回true,如果應將其濾除則返回false
使用explode
和in_array
檢查tag2
$filteredArray = array_filter($arr, "filterTag");
function filterTag($arrayElement) {
return in_array("tag2",explode(",",$arrayElement["tags"]));
}
您的嘗試不起作用,因為您的某些“標簽”包含除tags2
之外的其他單詞,例如tag1,tag2,tag3
做簡單的==
比較不會在字符串中搜索另一個字符串
您可以使用array_filter並提供正確的回調
$result = array_filter($arr,function($t){
return in_array('tag2',explode(',',$t['tags']));
});
$resultArr = array();
foreach($arr as $curr)
{
$tagsData = explode(',',$curr['tags']);
if(in_array('tag1',$tagsData)
$resultArr[] = $curr;
}
$ resultArr是包含帶有tag1標簽的數組的結果數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.