duangonglian6028 2017-12-29 01:22
浏览 21

计算foreach中的重复数字

Basically, I am fetching data from an API and that API has duplicate numbers. I want to count the duplicate numbers within the foreach, but its not working for some reason. I am not sure what I am doing wrong. You can see there is 33 many times. See the picture how it prints. It should be showing something like this

Array
(
    [33] => 5
    [2] => 3
)

Code:

foreach ($parsed_json1->numbers as $item) {
    $ui = $item->no;
    $currentp= number_format($ui, 6);
    //echo $currentp;
    //echo "</br>";

    $array = array($currentp);
    $vals = array_count_values($array);
   //echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
    print_r($vals);
}

enter image description here

  • 写回答

2条回答 默认 最新

  • douxin8749 2017-12-29 01:50
    关注

    The fundamental flaw of your code is that you take one value and format it, then you put it into array and then do array_count_values on it.

    See the difference:

    $arr = [33, 32, 23, 33, 22, 23, 32, 33, 33];
    
    print_r(array_count_values($arr));
    
    foreach($arr as $a) {
        $currentp= number_format($a, 6);
        $array = array($currentp);
        $vals = array_count_values($array);
        print_r($vals);
    
    }
    

    First print_r prints:

    Array
    (
        [33] => 4
        [32] => 2
        [23] => 2
        [22] => 1
    )
    

    And the print_r inside foreach prints:

    Array([33.000000] => 1)
    Array([32.000000] => 1)
    Array([23.000000] => 1)
    Array([33.000000] => 1)
    Array([22.000000] => 1)
    Array([23.000000] => 1)
    Array([32.000000] => 1)
    Array([33.000000] => 1)
    Array([33.000000] => 1)
    

    Do you realize the difference?

    I guess, what you need is

    $arr = (array_count_values([33, 32, 23, 33, 22, 23, 32, 33, 33]));
    $new_arr = [];
    
    foreach($arr as $k => $a) {
        $new_arr[number_format($k, 6)] = $a;
    }
    
    print_r($new_arr);
    

    Which outputs:

    Array
    (
        [33.000000] => 4
        [32.000000] => 2
        [23.000000] => 2
        [22.000000] => 1
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。