Reputation: 9476
I have array something like:
Array(
[06:30 PM] => 2
[03:00 AM] => 3
[08:00 PM] => 4
)
So I have used uksort to sort the key and array will be sorted like:
Array(
[03:00 AM] => 3
[06:30 PM] => 2
[08:00 PM] => 4
)
And code I have used is:
uksort($arr, function($a, $b) {
return (strtotime(date('H:i',strtotime($a))) > strtotime(date('H:i',strtotime($b))));
});
This array is have time in Key and count of value as value.Now, I have another array which contain the value of above keys.
Array
(
[1] => Array
(
[0] => Default
[1] => BHU
)
[2] => Array
(
[0] => Default
[1] => HOT
[2] => COLD
)
[3] => Array
(
[0] => Default
[1] => Test
[2] => Test1
[3] => Test2
)
)
Now, I want to sort this array also as per above array sorted. How can I do that?
Thanks
Upvotes: 2
Views: 86
Reputation: 436
<?php
$arr = array(
'06:30 PM' => 2,
'03:00 AM' => 3,
'08:00 PM' => 4,
);
$arr2 = array(
'1' => array(
'0' => 'Default',
'1' => 'BHU'
),
'2' => array(
'0' => 'Default',
'1' => 'HOT',
'2' => 'COLD',
),
'3' => array(
'0' => 'Default',
'1' => 'Test',
'2' => 'Test1',
'3' => 'Test2',
),
);
$arr3 = array_combine(array_keys($arr), $arr2);
uksort($arr3, function($a, $b) {
return (strtotime(date('H:i',strtotime($a))) > strtotime(date('H:i',strtotime($b))));
});
echo"<pre>";
print_r($arr3);
?>
Here in this example first use array_keys in your first array it will take your keys as value and than combine it with your another array for it you will use array_combine in array_combine it will get first array value as key and second array value as value and than sort your array as per key For more details you will refer this links:
http://php.net/manual/en/function.array-combine.php
http://php.net/manual/en/function.array-keys.php
Upvotes: 1
Reputation: 3743
First, the code you wrote can be simplified as
uksort($arr, function($a, $b) {
return ( strtotime($a) > strtotime($b) );
});
For the answer, It would be messy to make code for your array structure.
I would suggest making the following structure and then sorting with the code you wrote with little improvements i showed.
Check below,
Array
(
[06:30 PM] => Array
(
[0] => Default
[1] => BHU
)
[03:00 AM] => Array
(
[0] => Default
[1] => HOT
[2] => COLD
)
[08:00 PM] => Array
(
[0] => Default
[1] => Test
[2] => Test1
[3] => Test2
)
)
Upvotes: 1