dongzhuo6137 2015-06-16 09:43
浏览 28
已采纳

根据多维数组中的最新元素计算唯一值 - PHP

Well basically, I have a multidimentional array that I want to count state, but sometimes in the array I can get duplicate lid, so I got to get the lid with the newest date_add

[0] => Array
    (
        [lhid] => 181
        [lid] => 183
        [uid] => 1
        [state] => 2
        [date_add] => 2012-12-06 09:25:41
    )

[1] => Array
    (
        [lhid] => 198
        [lid] => 203
        [uid] => 1
        [state] => 1
        [date_add] => 2012-12-10 13:19:26
    )

[2] => Array
    (
        [lhid] => 222
        [lid] => 203
        [uid] => 1
        [state] => 1
        [date_add] => 2012-12-13 20:12:06
    )

Any way i can do this? Much appreciated!

Here's what have I tried so far and didn't succeed since it getr all the values :

$count = array();
foreach($stats_results as $state)
{
    @$count[$state['state']]++;
}

Here's the wanted format :

Array
(
    [1] => 110
    [2] => 4
    [0] => 4
    [3] => 2
)
  • 写回答

1条回答 默认 最新

  • dousi5501 2015-06-16 10:03
    关注
    // sort array by date in decreasing order
    usort($arr, function ($a, $b) { return strtotime($b['date_add']) - strtotime($a['date_add']); });
    
    $lids = array();    // used lids
    $result = array();
    
    foreach($arr as $item) 
       if (!in_array($item['lid'], $lids))  {       // If lid was before do nothing
          if (isset($result[$item['state']])) $result[$item['state']]++;
          else $result[$item['state']] = 1;
          $lids[] = $item['lid'];
       }
    
    var_dump ($result); 
    

    with your data result

    array(2) { [1]=> 1, [2]=> 1 }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP