0

I met a problem with array sorting.

My array's structure is like this:

array(4) {
  [1]=>
  array(5) {
    ["type"]=>
    string(4) "A"
    ["index"]=>
    int(1)
  }
  [2]=>
  array(5) {
    ["type"]=>
    string(4) "B"
    ["index"]=>
    int(4)
  }
  [3]=>
  array(5) {
    ["type"]=>
    string(4) "C"
    ["index"]=>
    int(2)
  }
  [4]=>
  array(5) {
    ["type"]=>
    string(4) "D"
    ["index"]=>
    int(3)
  }
}

As you can see, inside each child array, there's a key "index", and the value there was not in the correct order 1-2-3-4 but it's 1-4-2-3.

How I can sort this array so that its children arrays were listed in correct order ?

P.S.: The acutal array is much bigger&more complicated than this one.

JuLy
  • 483
  • 2
  • 5
  • 12
  • 2
    This question does not show any research effort. It is important to **do your homework**. Tell us what you found and ***why*** it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. [FAQ](http://stackoverflow.com/questions/how-to-ask). – Kermit Apr 08 '13 at 15:47
  • The link above helps, thx! – JuLy Apr 08 '13 at 15:54
  • For FreshPrinceOfSO , the time u spent on typing was already enough for answer the question – JuLy Apr 08 '13 at 15:57
  • @JuLy He copy-pasted :) – ypercubeᵀᴹ Apr 08 '13 at 19:30

3 Answers3

3
usort(
    $myArray,
    function ($a, $b) {
        if ($a['index'] == $b['index']) {
            return 0;
        }
        return ($a['index'] < $b['index']) ? -1 : 1;
    }
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • +1 for using an anonymous function, what will we be the preferred solution over a named function, as of php 5.3, in many situations. However there are still use cases where a named callback is useful. (+ thanks for helping me out with syntax errors! ) – hek2mgl Apr 08 '13 at 16:03
1

You can use the function usort() for this. It accepts an unsorted array and a callback function as its arguments. In the callback function you can define how elements should be compared. Here comes an example:

function compare($a, $b) {
    if($a['index'] === $b['index']) {
        return 0;
    }
    return $a['index'] < $b['index'] ? -1 : 1;
}

usort($array, 'compare');

Note: The callback can be an anonymous function or the name of a regular function. I've used a function name where @MarkBaker has used an anonymous function. So you have an example for both.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

A simple and fast solution for reindexing your array.

$old ; // Your old array
$new = array() ;
foreach ($old as $child){
  $new[$child['index']] = $child ;
}
sybear
  • 7,837
  • 1
  • 22
  • 38