简体   繁体   English

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

[英]Count unique values based on the newest element in a multidimentional array - 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 好吧,基本上,我有一个要计算state的多维数组,但是有时在数组中我可以得到重复的lid ,所以我必须使用最新的date_add来获得lid

[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
)
// 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 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM