Hi,

I'm using array_multisort to sort my multidim array, but,when I do, I lose index 0 of my array.

say my array is:

$nodes[0]=array("id"=>"32","order"=>1);
$nodes[1]=array("id"=>"24","order"=>2);
$nodes[2]=array("id"=>"25","order"=>4);
$nodes[5]=array("id"=>"12","order"=>6);

I know I skipped $nodes[4], but that can happen when the client removes a node in the database. When I use the following:

for($i = 0; $i < sizeof($nodes); $i++){
  $sortarray[] = $nodes[$i]['id'];
}
array_multisort($sortarray,$nodes);

I lose $nodes[0] during the array_multisort. A print_r of $sortarray and $nodes (before and after the array_multisort) reveals this. I've seen others on this list implement this without problems. I ended up using $sortarray for the ids. It's a kluge, but it gets the job done. I'd rather use the original array that I've sorted, though.

Thanks,
Biggus

    When I run your code I get this:

    Notice: Undefined offset: 3 [I]etc.[/I]
    
    $sortarray: 
    0 => 
    1 => 24
    2 => 25
    3 => 32

    With this code:

    for($i = 0; $i < sizeof($nodes); $i++) {
        if (isset($nodes[$i])) { 
            $sortarray[] = $nodes[$i]['id'];
        } else {
            $sortarray[] = '$nodes[' . $i . '] unset';
        } 
    } 
    array_multisort($sortarray, $nodes);

    I get this:

    $sortarray: 
    0 => $nodes[3] unset
    1 => 24
    2 => 25
    3 => 32
    

    and with this code:

    foreach ($nodes as $value) {
        $sortarray[] = $value['id'];
    }
    array_multisort($sortarray, $nodes);
    

    I get this:

    $sortarray: 
    0 => 12
    1 => 24
    2 => 25
    3 => 32

    This block:

    for($i = 0; $i < sizeof($nodes); $i++){ 
      $sortarray[] = $nodes[$i]['id']; 
    }

    fails to reach offset 5, since the size of "$nodes" is only 4, and the unset element is evaluated to null.

    All three, of course, result in this for "$nodes":

    $nodes: 
    0 => Array
    id => 12
    order => 6
    1 => Array
    id => 24
    order => 2
    2 => Array
    id => 25
    order => 4
    3 => Array
    id => 32
    order => 1
    

    ("array_multisort()" resets the numeric indexes.)

      thanks, Installer, not sure why I didn't think of foreach. It works perfectly now.

      Thanks again,
      Biggus

        Write a Reply...