如何避免 foreach 循环以及我们如何使用数组列

How to avoid forech loop and how we can use array column

我有一个数组,在这个数组中我有列 price,现在我想只取价格等于 5 以及大于 5 的价格。我知道使用 foreach 循环我们可以实现这一点,还有其他方法可以达到我的预期答案吗?

$mainArray = [
    "key1" => ["name" => "A", "price" => 5],
    "key2" => ["name" => "B", "price" => 7],
    "key3" => ["name" => "C", "price" => 2],
    "key4" => ["name" => "D", "price" => 9]
];

MY CODE

  <?php
$mainArray = [
    "key1" => ["name" => "A", "price" => 5],
    "key2" => ["name" => "B", "price" => 7],
    "key3" => ["name" => "C", "price" => 2],
    "key4" => ["name" => "D", "price" => 9]
];

$maxPrice = 5;
$mainArray = array_filter($mainArray, function($value) {
    return $value['price'] >= $maxPrice;
});


print_r($mainArray);

?>

但我收到错误 E_NOTICE : type 8 -- Undefined variable: maxPrice -- at line 11

您可以使用 array_filter 检查价格是否等于或大于 5。

<?php
$mainArray = [
    "key1" => ["name" => "A", "price" => 5],
    "key2" => ["name" => "B", "price" => 7],
    "key3" => ["name" => "C", "price" => 2],
    "key4" => ["name" => "D", "price" => 9]
];

$maxPrice = 5;
$mainArray = array_filter($mainArray, function($value) use ($maxPrice) {
    return $value['price'] >= 5;
});


var_dump($mainArray);

试试这个方法:

<?php
$mainArray = [
  "key1" => ["name" => "A", "price" => 5],
  "key2" => ["name" => "B", "price" => 7],
  "key3" => ["name" => "C", "price" => 2],
  "key4" => ["name" => "D", "price" => 9]
];
$min = 5;
$result = array_filter(
  $array_column(mainArray, 'price'),
   function ($value) use($min) {
      return ($value >= $min);
   }
);