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

时间:2015-06-16 09:43:09

标签: php arrays count

基本上,我有一个我希望计算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
)

1 个答案:

答案 0 :(得分:0)

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