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);
$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>";
if you want to reset array keys then you can use
$final_array = array_values($final_array);
echo "<pre>";
print_r($final_array);
echo "</pre>";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.