alex
alex

Reputation: 4914

How to sort a php associative array to a specific order?

this is the array i like to sort in a particular order

$aData = Array
  (
    [break] => Array
        (
            [Indoor room] => 42
            [Gym Class] => 19
        )
    [finish] => Array
        (
            [Indoor room] => 42
            [Gym Class] => 19
        )

    [lunch] => Array
        (
            [Indoor room] => 7
        )

    [period1] => Array
        (
            [Indoor room] => 12
            [Gym Class] => 22
        )

    [period2] => Array
        (
            [Gym Class] => 14
            [Indoor room] => 25
        )

    [period3] => Array
        (
            [Gym Class] => 21
            [Indoor room] => 11
        )

    [period4] => Array
        (
            [Gym Class] => 22
            [Indoor room] => 20
        )

    [period5] => Array
        (
            [Gym Class] => 16
            [Indoor room] => 9
        )

)

But i like it in this order:

break, period1, period2, lunch, period3, period5, period6, finish

for this I am trying the following php code

$arraySort = [
  "break",  
  "period1", 
  "period2", 
  "period3", 
  "lunch",
  "period4",
  "period5", 
  "period6", 
  "finish" 
];

   foreach($aData as $period => $catsScore){
  echo 'test '.$period.'<br/>';  
  $periodItem = [$period];
  foreach($arraySort as $cat){
      echo 'new: '.$cat.'<br/>';
      $periodItem[] = $catsScore;
  }
  $output[] = $periodItem;
    }


print_r($output);

Upvotes: 5

Views: 2032

Answers (4)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

Easy- Just use the arraySort as the assoc key and get the corresponding array / value from the original array,

<?php

$arraySort = [
  "break",  
  "period1", 
  "period2", 
  "period3", 
  "lunch",
  "period4",
  "period5", 
  "period6", 
  "finish" 
];

$final_array = [];

foreach($arraySort  as $arraySo){
  $final_array[$arraySo] = isset($aData[$arraySo]) ? $aData[$arraySo] : [];
}

print_r($final_array);

Output:- https://3v4l.org/4LXvS

Upvotes: 5

Sammitch
Sammitch

Reputation: 32232

Alternatively you could use an actual sorting function:

uksort(
    $aData,
    function($a,$b)use($arraySort){
        return array_search($a, $arraySort) - array_search($b, $arraySort);
    }
);

Upvotes: 1

splash58
splash58

Reputation: 26153

Make correctly ordered array and fill it by value from source array

$final_array = array_replace(array_fill_keys($arraySort, []), $aData);

demo

Upvotes: 3

Ali
Ali

Reputation: 3666

you can use array_combine for this purpose:

$arrary_sort = ["break", "period1"];
$final_array = array_combine($array_sort, $your_array_here);

Upvotes: 0

Related Questions