I am trying to figure out how to only output unique IDs that are above 30 seconds in this array. to make it simple it just needs to grab the first value over 30 seconds for a unique 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'
));
Ideal result would look like this
$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'
));
Currently I can only get unique values for the ID's without having the seconds correlated with the 'id' field.
You can use array_reduce
to iterate over the $array
and extract only values that you want.
$array = array_reduce($array, function ($unique, $entry) {
extract($entry);
if (! isset($unique[$id]) && $seconds > 30) {
$unique[$id] = $entry;
}
return $unique;
}, []);
$array = array_values($array);