假设我有一个包含这些值的数组:
$arr = [
['type' => 'gallery', 'value' => 'foo'],
['type' => 'gallery', 'value' => 'foo2'],
['type' => 'gallery', 'value' => 'foo3'],
['type' => 'featured', 'value' => 'test'],
];
我需要找到所有gallery
个出现的地方,所以我做到了:
$key = array_search('gallery', array_column($arr, 'type'));
if($arr[$key] !== false)
{
var_dump($arr[$key]);
}
但此打印仅出现一种情况:
['type'=>'图库','value'=>'foo3'],
答案 0 :(得分:1)
<?php $arr = [
['type' => 'gallery', 'value' => 'foo'],
['type' => 'gallery', 'value' => 'foo2'],
['type' => 'gallery', 'value' => 'foo3'],
['type' => 'featured', 'value' => 'test'],
];
$new = array_filter($arr, function ($var) {
return $var['type'] == 'gallery';
});
echo "<pre>";
print_r($new);
编辑:如果需要互换,则可以稍作修改:
$filterBy = 'gallery'; // or Finance etc.
$new = array_filter($arr, function ($var) use ($filterBy) {
return ($var['type'] == $filterBy);
});
输出
Array
(
[0] => Array
(
[type] => gallery
[value] => foo
)
[1] => Array
(
[type] => gallery
[value] => foo2
)
[2] => Array
(
[type] => gallery
[value] => foo3
)
)
答案 1 :(得分:1)
这是一个基本的数组过滤问题。所提供的解决方案只是众多可能解决方案之一。
$arr = [
['type' => 'gallery', 'value' => 'foo'],
['type' => 'gallery', 'value' => 'foo2'],
['type' => 'gallery', 'value' => 'foo3'],
['type' => 'featured', 'value' => 'test'],
];
// filter out other types. make sure only 'gallery' types are returned to the new array $arrOnlyGallery.
// You can use a for loop too here.
$arrOnlyGallery = array_filter($arr, function($a) {
return $a['type'] == 'gallery';
});
// show the array which should only contain 'gallery' types.
var_dump($arrOnlyGallery);
输出:
array(3){[0] => array(2){[“” type“] =>字符串(7)” gallery“ [” value“] => string(3)“ foo”} 1 => array(2){[“ type”] => string(7)“ gallery” [“ value”] =>字符串(4)“ foo2”} [2] =>数组(2){[“” type“] =>字符串(7) “ gallery” [“ value”] =>字符串(4)“ foo3”}}
您可以阅读有关PHP数组过滤here的更多信息。
答案 2 :(得分:1)
尝试
function getGallery($var)
{
return($var['type'] == 'gallery');
}
$arr = [
['type' => 'gallery', 'value' => 'foo'],
['type' => 'gallery', 'value' => 'foo2'],
['type' => 'gallery', 'value' => 'foo3'],
['type' => 'featured', 'value' => 'test'],
];
$filteredArr = array_filter($arr,"getGallery");
答案 3 :(得分:1)
您只需要简单地执行array_filter,它将得到预期的结果。
$searchResult = array_filter($arr, function($v, $k) {
return $v['type'] == "gallery";
}, ARRAY_FILTER_USE_BOTH);
print_r($searchResult);`