0

Problem: I have an associative multi-dimensional array with each key having an array inside. It looks like this:

array(3){
     [1]=>
          "id"=>1
          "name"=>"Test #1"
          "listorder"=>1
     [6]=>
          "id"=>6
          "name"=>"Test #1"
          "listorder"=>3
     [2]=>
          "id"=>2
          "name"=>"Test #2"
          "listorder"=>2
}

I need to sort this array by each array's listorder value without changing any of the key numbers. How can this be done?

I am currently trying this code which I got from a separate Stack overflow question.

function sort_array(){
    foreach($array as $key => $row){
        $listorder[$row["id"]] = $row["listorder"];
    }
    array_multisort($listorder, SORT_ASC, $array);
    return $array;
}

But this specific code rewrites all of the key numbers. Is there another way to sort without changing anything?

ZeroByter
  • 309
  • 1
  • 7
  • 19

3 Answers3

2

The best possible way is to use uasort() function.

Try this:

$array  =   array(
    1 => array(
      "id"=>1,
      "name"=>"Test #1",
      "listorder"=>1
    ),
    6   =>  array(
        "id"=>6,
        "name"=>"Test #1",
        "listorder"=>3
    ),  
    2   =>  array(
        "id"=>2,
        "name"=>"Test #2",
        "listorder"=>2
    )   
);


function sort_count($a, $b) {
    if ($a['listorder'] === $b['listorder']) {
      return 0;
    } else {
       return ($a['listorder'] > $b['listorder'] ? 1:-1);
    }
}

$sorted_array = uasort($array, 'sort_count');

echo "<pre>";
print_r($array);
echo "</pre>";
Object Manipulator
  • 8,485
  • 2
  • 9
  • 25
0

you can try to sort by creating a new array, with array_keys:

function sort_array($array)
{
    $keys = array_keys($array);

    $out = array();
    $listorder = array();

    foreach($array as $key => $row)
    {
        $listorder[$row["id"]] = $row["listorder"];
    }


    array_multisort($listorder, SORT_ASC, $keys);
    foreach($keys as $k)
    {
        $out[$k] = $array[$k];
    }


    return $out;
}

It should only sort the 'keys' array (which contain keys of array).

And then you rebuild the sorted $array in $out

Vincent
  • 950
  • 5
  • 11
0

You can try this short and sweet piece of code:

uasort($data,function($a,$b){
    return strcmp($a["listorder"],$b["listorder"]);
});
print_r($data);

Working Demo is Here

Ali
  • 1,260
  • 9
  • 14