0

I am trying to sort a multidimensional array by multiple keys without affecting previously sorted array's index. I can only try to sort the first time using the name key. I am not sure how to sort again the array with the next key without affecting the order of previously sorted array.

My array looks like this:

$columns = ['model', 'color'];
$data = [
    [
        'name' => 'Joe Smith',
        'model' => 'Honda',
        'color' => 'yellow'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Honda',
        'color' => 'red'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Toyota',
        'color' => 'red'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Tesla',
        'color' => 'orange'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Tesla',
        'color' => 'aqua'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Volkswagen',
        'color' => 'teal'
    ],
    [
        'name' => 'Joe Smith',
        'model' => 'Honda',
        'color' => 'blue'
    ],
];

foreach($data as $value) {
    $row = [];

    foreach($columns as $column) {
        $row[] = $value[$column];
    }

    $sheet[] = $row;
}
B. Fleming
  • 7,170
  • 1
  • 18
  • 36
MiniDr
  • 191
  • 1
  • 11
  • What do you want the output to that example input to be? – Shardj May 24 '19 at 10:23
  • Also I'm not sure how you expect to be able to sort anything if you cant change the index. What do you actually need this for? – Shardj May 24 '19 at 10:24
  • 1
    Possible duplicate of [PHP sort array by two field values](https://stackoverflow.com/questions/4582649/php-sort-array-by-two-field-values) – Yassine CHABLI May 24 '19 at 10:34
  • I am sorry, I mean you can change the index. I got rows of data and above array is sorted by name. So, next sorting would be `model`. Therefore, Honda, Honda, Honda, Tesla, Tesla, Toyota, and Volkswagen. Next sorting would be color. So, in my previously sorted array which is sorted by model, is there a way to sort the color. There are 3 Hondas and I want to sort the color – MiniDr May 24 '19 at 10:34

0 Answers0