Hey All I have this object in php. that I want to sort by timestamp the array in variable $tempData
array (
0 =>
array (
'Timestamp' => '2022-02-21 06:00',
'Date' => '2022-02-21',
'Hour' => '06',
),
1 =>
array (
'Timestamp' => '2022-02-21 08:00',
'Date' => '2022-02-21',
'Hour' => '08',
),
2 =>
array (
'Timestamp' => '2022-02-21 03:00',
'Date' => '2022-02-21',
'Hour' => '03',
),
3 =>
array (
'Timestamp' => '2022-02-21 00:00',
'Date' => '2022-02-21',
'Hour' => '00',
),
)
I try this code from https://stackoverflow.com/questions/1597736/how-to-sort-an-array-of-associative-arrays-by-value-of-a-given-key-in-php
$sortedArray = array();
foreach ($tempData as $key => $row)
{
$sortedArray[$key] = $row['Timestamp'];
}
array_multisort($sortedArray, SORT_DESC, $tempData);
And the result is
[2022-02-21 05:26:30] local.INFO: The sorted data are:
[2022-02-21 05:26:30] local.INFO: array (
0 => '2022-02-21 06:00',
1 => '2022-02-21 08:00',
2 => '2022-02-21 03:00',
3 => '2022-02-21 00:00',
However I need all the origin array to be displayed, all the objects . meaning it will be the same object as $tempData with all the nodes, but sorted and not just to sort the field. can someone advise?
I tried also this code:
function asc_sort_json($array1,$array2){
$on = 'Timestamp';
if ($array1[$on] == $array2[$on]) {
return 0;
}
return ($array1[$on] < $array2[$on]) ? -1 : 1;
}
usort($tempData, "asc_sort_json");
and get this error:
local.ERROR: usort() expects parameter 2 to be a valid callback, function 'asc_sort_json' not found or invalid function name {"exception":"[object] (ErrorException(code: 0): usort() expects parameter 2 to be a valid callback, function 'asc_sort_json' not found or invalid function name at
CodePudding user response:
$tempData = [
[
'Timestamp' => '2022-02-21 06:00',
'Date' => '2022-02-21',
'Hour' => '06',
],
[
'Timestamp' => '2022-02-21 08:00',
'Date' => '2022-02-21',
'Hour' => '08',
],
[
'Timestamp' => '2022-02-21 03:00',
'Date' => '2022-02-21',
'Hour' => '03',
],
[
'Timestamp' => '2022-02-21 00:00',
'Date' => '2022-02-21',
'Hour' => '00',
],
];
$Timestamp = array_column($tempData, 'Timestamp');
array_multisort($Timestamp, SORT_DESC, $tempData);
print_r($tempData);
Output:
Array
(
[0] => Array
(
[Timestamp] => 2022-02-21 08:00
[Date] => 2022-02-21
[Hour] => 08
)
[1] => Array
(
[Timestamp] => 2022-02-21 06:00
[Date] => 2022-02-21
[Hour] => 06
)
[2] => Array
(
[Timestamp] => 2022-02-21 03:00
[Date] => 2022-02-21
[Hour] => 03
)
[3] => Array
(
[Timestamp] => 2022-02-21 00:00
[Date] => 2022-02-21
[Hour] => 00
)
)