PHP-过滤关联数组的数组[duplicate]

vuktfyat  于 2022-12-02  发布在  PHP
关注(0)|答案(1)|浏览(146)

此问题在此处已有答案

array_filter with assoc array?(2个答案)
2天前关闭。
所有。我相信有人可能问过类似的事情,但我没有找到相关的线程。我有以下数组的关联数组
我可以知道如何提取一个只有[type] => Beverage的数据数组吗?

Array ( 
    [0] => Array ( 
        [id] => 1 
        [prod_name] => Coffee 
        [type] => Beverage 
    ) 
    [1] => Array ( 
        [id] => 2 
        [prod_name] => Vegetable 
        [type] => Food 
    )
    [2] => Array ( 
        [id] => 3 
        [prod_name] => Orange Juice 
        [type] => Beverage 
    )
)

我已经看了函数数组过滤器,但仍然不能弄清楚答案。谢谢。

cczfrluj

cczfrluj1#

您可以使用array_filter轻松完成此操作:

$data = [
    ['id' => 1, 'prod_name' => 'Coffee', 'type' => 'Beverage'],
    ['id' => 2, 'prod_name' => 'Vegetables', 'type' => 'Food'],
    ['id' => 3, 'prod_name' => 'Orange Juice', 'type' => 'Beverage'],
];

$output = array_filter($data, function ($record) {
    if ($record['type'] == 'Beverage')
        return $record;
});

var_dump($output);

产量:

array(2) {
  [0]=>
  array(3) {
    ["id"]=>
    int(1)
    ["prod_name"]=>
    string(6) "Coffee"
    ["type"]=>
    string(8) "Beverage"
  }
  [2]=>
  array(3) {
    ["id"]=>
    int(3)
    ["prod_name"]=>
    string(12) "Orange Juice"
    ["type"]=>
    string(8) "Beverage"
  }
}

相关问题