php - 如何检索具有特定列值的数组列表?

标签 php

假设我有一个包含这些值的数组:

$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/

相关文章:

java vs. php 以 html 形式使用 post

php - 为什么 Laravel 供应商是 :publish returning "Unable to locate publishable resources"?

php - Kohana3 : Different . htaccess rewritebase 和 kohana base_url 用于开发和生产环境

php - PDO更改查询

PHP 要求与自动加载

php - 如何在不在开发服务器上运行的情况下设置 PHPUnit 测试框架?

php - 如何在php中显示带有列名的json数据

php - 获取 MySQL LEFT JOIN 上最后一次出现的行

php - 从指定的字符串创建新数组?

javascript - 一个 onchange 具有 2 个功能