我试图找出如何仅在此数组中输出超过30秒的唯一ID。为了简单起见,只需要在30秒内获取第一个值以获得唯一ID。
$array = array(
0 => array(
'id' => '1',
'seconds' => '36'
),
1 => array(
'id' => '1',
'seconds' => '60'
),
2 => array(
'id' => '1',
'seconds' => '36'
),
3 => array(
'id' => '2',
'seconds' => '22'
),
4 => array(
'id' => '1',
'seconds' => '36'
),
5 => array(
'id' => '2',
'seconds' => '36'
),
6 => array(
'id' => '3',
'seconds' => '44'
),
7 => array(
'id' => '3',
'seconds' => '2'
),
8 => array(
'id' => '4',
'seconds' => '58'
),
9 => array(
'id' => '6',
'seconds' => '9'
),
10 => array(
'id' => '6',
'seconds' => '8'
));
理想的结果看起来像这样
$arrayResult = array(
0 => array(
'id' => '1',
'seconds' => '36'
),
1 => array(
'id' => '2',
'seconds' => '36'
),
2 => array(
'id' => '3',
'seconds' => '44'
),
3 => array(
'id' => '4',
'seconds' => '58'
));
目前,我只能获取ID的唯一值,而不会将秒与“ID”相关联。字段。
答案 0 :(得分:2)
您可以使用array_reduce
来迭代$array
并仅提取您想要的值。
$array = array_reduce($array, function ($unique, $entry) {
extract($entry);
if (! isset($unique[$id]) && $seconds > 30) {
$unique[$id] = $entry;
}
return $unique;
}, []);
$array = array_values($array);
答案 1 :(得分:1)
$final_array = array();
foreach($array as $val)
{
if($val['seconds'] > 30 && (!array_key_exists($val['id'], $final_array))){
$final_array[$val['id']] = $val;
}
}
echo "<pre>";
print_r($final_array);
echo "</pre>";
如果要重置数组键,则可以使用
$final_array = array_values($final_array);
echo "<pre>";
print_r($final_array);
echo "</pre>";