-2
有一個數組:PHP:檢查,什麼陣列值大於1(複製等)
Array
(
[Apple] => 1
[Banana] => 2
[Orange] => 1
[Pie] => 3
)
我想檢查一下,有什麼陣列值大於1(副本等)並返回它們。
'Banana was found 2 times in the array, Pie even 3 times.
有一個數組:PHP:檢查,什麼陣列值大於1(複製等)
Array
(
[Apple] => 1
[Banana] => 2
[Orange] => 1
[Pie] => 3
)
我想檢查一下,有什麼陣列值大於1(副本等)並返回它們。
'Banana was found 2 times in the array, Pie even 3 times.
您可以使用array_filter過濾基於鍵/值的數組。它只返回一個數組,其中只有匹配回調函數中的條件。
$greaterThanOne = array_filter($array, function($val){ return ($val > 1); });
foreach($greaterThanOne as $fruit=>$count){
echo "$fruit was found $count times in the array.<br>";
}
你只需要遍歷數組...
foreach ($array_with_fruits as $fruit=>$times){
if ($times>1) { echo $fruit." was found ".$times." times"; }
}
大。玩的開心! –
@Lightness在軌道上的比賽:我應該提到,我一直在尋找儘可能高效的解決方案。 – Ben