为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
紫衣仙女 2021-07-02 09:09:21
我有一个数组,在这个数组中我有列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 回答

?
慕虎7371278

TA贡献1802条经验 获得超4个赞

您可以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);


查看完整回答
反对 回复 2021-07-09
?
胡子哥哥

TA贡献1825条经验 获得超6个赞

试试这个方法:


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

   }

);


查看完整回答
反对 回复 2021-07-09
  • 2 回答
  • 0 关注
  • 134 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信