I am trying to sort an array using sort () but it does not work

 if ( $_GET['_value'] == 'moto'  )
     {
        $array[] = array('1' => 'Yamaha');
        $array[] = array('2' => 'Suzuki');  
        $array[] = array('3' => 'Triumph');
        $array[] = array('4' => 'KTM');
        $array[] = array('5' => 'Honda');
        $array[] = array('6' => 'Harley Davidson');
        $array[] = array('7' => 'Buell');
        $array[] = array('8' => 'MV Agusta');
        $array[] = array('9' => 'Ducati');
        $array[] = array('10' => 'Other');

      } 
 $array = sort($array);
 echo json_encode( $array );

that is, the code that I have, and the chained drop-down list pulled it out. I want it to return values ​​sorted alphabetically, but based on the code you see returns an empty array. what could be the mistake i am making /

+2
source share
4 answers

It's not pretty at all, but it does the job.

If you are not limited, otherwise you really should use some other suggestions.

<?
if ( $_GET['_value'] == 'moto'  ) {
    $array[] = array('1' => 'Yamaha');
    $array[] = array('2' => 'Suzuki');  
    $array[] = array('3' => 'Triumph');
    $array[] = array('4' => 'KTM');
    $array[] = array('5' => 'Honda');
    $array[] = array('6' => 'Harley Davidson');
    $array[] = array('7' => 'Buell');
    $array[] = array('8' => 'MV Agusta');
    $array[] = array('9' => 'Ducati');
    $array[] = array('10' => 'Other');
    foreach($array as $i => $v)
    {
        $v = array_values($v);
        $sort[] = $v[0];
    }
    sort($sort);
    $c = 0;
    foreach($sort as $i => $v)
    {
        $c++;
        $sorted[] = array($c=>$v);
    }

    echo json_encode($sorted);
}
?>
+1
source

, . "sort php array by sub-array key", - :

$array[1] = 'Yamaha';
$array[2] = 'Suzuki'; 
// ...
sort($array);
echo json_encode($array);
+4

, , :

$array[1] = 'Yamaha';       

$array[2] = 'Suzuki';     

then sort($array)

+3
source

You can use uasort () function

as:

function cmp($a, $b) {
    $a = reset($a);
    $b = reset($b);
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

uasort($array, 'cmp')
+2
source

All Articles