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


Count unique values based on the newest element in a multidimentional array - PHP

基本上,我有一个多维数组,我想state计数,但有时在数组中我可能会得到重复的lid,所以我必须得到最新的lid 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
    )

有什么办法可以做到这一点吗?非常感谢!

以下是我到目前为止尝试过但没有成功的方法,因为它获得了所有值:

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

这是想要的格式:

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); 

使用您的数据结果

array(2) { [1]=> 1, [2]=> 1 }