I’ve got a multidimensional array that I want to sort alphabetically by the values of specific key. Structure of the array is –
Array ( [sr] => Array ( [2] => 1 [3] => 2 [4] => 3 [5] => 4 [6] => 5 [7] => 6 [8] => 7 [9] => 8 [10] => 9 ) [deptt] => Array ( [2] => KKT-TICKETING [3] => KKT-TICKETING [4] => KKT-TICKETING [5] => KKT-HOTELS [6] => KKT-TICKETING [7] => KKT-HOTELS [8] => GTT-TICKETING [9] => GTT-HOTELS [10] => GTT-TICKETING )
I wanted to sort the data on basis of key ‘deptt’ alphabetically by the values. My desired output should be like all ‘GTT-HOTELS’ data should shown first then ‘KKT-HOTELS’ –
[deptt] => Array ( [2] => GTT-HOTELS [3] => GTT-TICKETING [4] => GTT-TICKETING [5] => KKT-HOTELS [6] => KKT-HOTELS [7] => KKT-TICKETING [8] => KKT-TICKETING [9] => KKT-TICKETING [10] => KKT-TICKETING ) with corresponding values of key 'sr'.
Any ideas how to do this? Hope I could make you understand the scenario.
Advertisement
Answer
Given this data:
$data = [ 'sr' => [ 2 => 1, 3 => 2, 4 => 3, 5 => 4, 6 => 5, 7 => 6, 8 => 7, 9 => 8, 10 => 9, ], 'deptt' => [ 2 => 'KKT-TICKETING', 3 => 'KKT-TICKETING', 4 => 'KKT-TICKETING', 5 => 'KKT-HOTELS', 6 => 'KKT-TICKETING', 7 => 'KKT-HOTELS', 8 => 'GTT-TICKETING', 9 => 'GTT-HOTELS', 10 => 'GTT-TICKETING', ] ];
The below code can be used. The magic is in the array_combine
function which merges two arrays, using one for the keys and one for the values. However, in both cases, it takes the values of those arrays, so you need to call array_keys
on the former to get those as values.
// Grab our arrays as variables $sr = $data['sr']; $deptt = $data['deptt']; // Sort the latter by values alphabetically sort($deptt); // Merge them together, keys from the first and values from the second $final = array_combine(array_keys($sr), $deptt);
This produces the following:
array ( 2 => 'GTT-HOTELS', 3 => 'GTT-TICKETING', 4 => 'GTT-TICKETING', 5 => 'KKT-HOTELS', 6 => 'KKT-HOTELS', 7 => 'KKT-TICKETING', 8 => 'KKT-TICKETING', 9 => 'KKT-TICKETING', 10 => 'KKT-TICKETING', )
Additional care should be taken to make sure that both arrays have the same number of items. array_combine
will return false in that case.