根据多维数组中的最新元素计算唯一值 - 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 }
基本上,我有一个多维数组,我想计算 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 }