【问题标题】:PHP: Check, what array values are greater than 1 (duplicates etc.) [closed]PHP:检查,哪些数组值大于 1(重复等)[关闭]
【发布时间】:2012-12-07 22:20:52
【问题描述】:

有一个数组:

Array
(
    [Apple] => 1
    [Banana] => 2
    [Orange] => 1
    [Pie] => 3
)

我想检查一下,哪些数组值大于 1(重复等)并返回它们。

'Banana was found 2 times in the array, Pie even 3 times.

【问题讨论】:

  • @Lightness Races in Orbit:我应该提到,我正在寻找一种尽可能高效的解决方案。

标签: php arrays string


【解决方案1】:

您可以使用 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>";
}

【讨论】:

    【解决方案2】:

    你只需要迭代数组...

    foreach ($array_with_fruits as $fruit=>$times){
        if ($times>1) { echo $fruit." was found ".$times." times"; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2013-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多