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

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


紫衣仙女
浏览 135回答 2
2回答

慕虎7371278

您可以array_filter用来检查价格是否等于或大于 5。<?php$mainArray = [&nbsp; &nbsp; "key1" => ["name" => "A", "price" => 5],&nbsp; &nbsp; "key2" => ["name" => "B", "price" => 7],&nbsp; &nbsp; "key3" => ["name" => "C", "price" => 2],&nbsp; &nbsp; "key4" => ["name" => "D", "price" => 9]];$maxPrice = 5;$mainArray = array_filter($mainArray, function($value) use ($maxPrice) {&nbsp; &nbsp; return $value['price'] >= 5;});var_dump($mainArray);

胡子哥哥

试试这个方法:<?php$mainArray = [&nbsp; "key1" => ["name" => "A", "price" => 5],&nbsp; "key2" => ["name" => "B", "price" => 7],&nbsp; "key3" => ["name" => "C", "price" => 2],&nbsp; "key4" => ["name" => "D", "price" => 9]];$min = 5;$result = array_filter(&nbsp; $array_column(mainArray, 'price'),&nbsp; &nbsp;function ($value) use($min) {&nbsp; &nbsp; &nbsp; return ($value >= $min);&nbsp; &nbsp;});
打开App,查看更多内容
随时随地看视频慕课网APP