-3

I have an array like this:

[ ["5", "France", "Paris", "..."], ["7", "UK", "London"], ["1", "..."], ["8", "..."] ]

Now I need to sort this one array so that the individual entries are in order like this:

[ ["1", "..."], ["5", "France",  "Paris"], ["7", "UK", "London"], ["8", "..."] ]

How would I go about that in PHP?

The other answer that @YourCommonSense is referring to does it in Java and not in PHP

D. Krold
  • 25
  • 7

2 Answers2

0

You don't need jQuery to do it in Javascript

var arr = [ ["5", "France", "Paris", "..."], ["7", "UK", "London"], ["1", "..."], ["8", "..."] ]
console.log(arr);
arr.sort((el1,el2) => {
    return el1[0] - el2[0];
});

// Non-ES6 equivalent
arr.sort(function(el1,el2) {
    return el1[0] - el2[0];
});

console.log(arr);

Output:

[["5", "France", "Paris", "..."], ["7", "UK", "London"], …]
[["1", "..."], ["5", "France", "Paris", "..."], ["7", …], …]
ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81
  • What does el1 and el2 stand for? – D. Krold Dec 17 '17 at 10:30
  • `.sort()` receives a [comparingFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) which tells it how to decide the order of two elements. The two elements in this case are arrays themselves since your original array contains arrays inside – ᴘᴀɴᴀʏɪᴏᴛɪs Dec 17 '17 at 10:33
  • And do I have to define el1 and el2 or will it do that automatically? – D. Krold Dec 17 '17 at 11:14
  • The callback (`function(el1,el2)...`) will be called multiple times when sorting and each time `el1`, `el2` will be provided so no you don't need to define it yourself – ᴘᴀɴᴀʏɪᴏᴛɪs Dec 17 '17 at 12:10
  • Good, thanks. I read the article for comparingFunction too and it helped me as well! Thanks a lot! – D. Krold Dec 17 '17 at 12:15
0

One solution PHP oriented

usort($array, function($a, $b){
    return strcmp($a[0], $b[0]);
});
print_r($array);

Result

Array ( [0] => Array ( [0] => 1 [1] => ... )

[1] => Array
    (
        [0] => 5
        [1] => France
        [2] => Paris
        [3] => ...
    )

[2] => Array
    (
        [0] => 7
        [1] => UK
        [2] => London
    )

[3] => Array
    (
        [0] => 8
        [1] => ...
    ) )
Mauricio Florez
  • 1,112
  • 8
  • 14