假设我有一个包含这些值的数组:
$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' => 'gallery', 'value' => 'foo3'],
最佳答案
这是一个基本的数组过滤问题。所提供的解决方案只是众多可能的解决方案之一。
$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"]=> string(7) "gallery" ["value"]=> string(3) "foo" } 1=> array(2) { ["type"]=> string(7) "gallery" ["value"]=> string(4) "foo2" } [2]=> array(2) { ["type"]=> string(7) "gallery" ["value"]=> string(4) "foo3" } }
您可以阅读有关 PHP 数组过滤的更多信息 here .
关于php - 如何检索具有特定列值的数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58657219/