dsbx40787736 2017-11-12 10:14
浏览 20
已采纳

如果是,检查数组中是否存在键,计算它并创建一个新的数组php

From my SQL query, I will get the following array as a result. This is the last result I can get from SQL.I cant change any SQL because of some constraint. I need to check if the same id exists or not and if it does need to count them and remove one of the duplicate array having the same id. Sample array is

$array = array(
          0 => array(
            'id' => '17',
            'status' => 1,


          ),
          1 => array(
            'id' => '18',
            'status' => 1,


          ),
          2 => array(
            'id' => '21',
            'status' => 1,


          ),
          3 => array(
            'id' => '5',
            'status' => 2,


          ),
          4 => array(
            'id' => '18',
            'status' => 1,


          ),
          5 => array(
            'id' => '22',
            'status' => 5,


          ),
          6 => array(
            'id' => '6',
            'status' => 1,


          ),
        );

I need to check if they have a duplicate id or not, if yes need to count them and remove one of the duplicates.We need to preserve the array structure.

End Results should be

array(
  0 => array(
    'id' => '17',
    'status' => 1,
'count'=1,

  ),
  1 => array(
    'id' => '18',
    'status' => 1,
'count'=2,



  ),
  2 => array(
    'id' => '21',
    'status' => 1,
'count'=1,


  ),
  3 => array(
    'id' => '5',
    'status' => 2,
'count'=1,


  ),
  4 => array(
    'id' => '22',
    'status' => 5,
'count'=1,


  ),

  5 => array(
    'id' => '6',
    'status' => 1,
'count'==>1,
  ),
)
  • 写回答

2条回答 默认 最新

  • dongpin1850 2017-11-12 12:46
    关注

    You can Check it by this way but duplicate entry still in the array.

    $ids = array();
    
    foreach ($array as $key => $value) 
    {
       $ids[] = $value['id'];
       $count = array_count_values($ids);
    }
    
    for($i = 0; $i < count($array);$i++)
    {
    
      $array[$i]['count'] = $count[$array[$i]['id']];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮