如何避免forech循环以及如何使用数组列

时间:2019-05-24 05:32:36

标签: php php-7

我有一个数组,在这个数组中我有列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]
];
  

我的密码

  <?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

2 个答案:

答案 0 :(得分:2)

您可以使用<?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); 检查价格是否等于或大于5。

{{1}}

答案 1 :(得分:1)

尝试这种方式:

<?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);
   }
);