简体   繁体   中英

Sort the array in descending order

I need to sort the array in descending order. I use asort in order to save proper reference to keys. However, $ind is null. Why?

$selected = array();

for ($i=0; $i<10; $i++) {
    $selected[] = array('ind' => $i, 'rank' => rand(0,10));
}

asort($selected, SORT_NUMERIC);

$ind = $selected['ind'];

After your for() loop you have something like this:

Array ( 
   [0] => Array (
      [ind] => NUM
      [rank] => NUM 
   [1] => Array (
      [ind] => NUM
      [rank] => NUM
   etcetcetc....
)

This is called a multidimensional array, and you access the inner arrays in a similar way as you do single-dimensional arrays.

You can access it with a $array[0]['ind'] , or possibly even a foreach() loop so you get all the values.

$ind = array();
foreach($array as $line) {
   $ind[] = $line['ind'];
}

Now the $ind array has all the values in a single-dimensional array, that you can access with: $ind[0] or $ind[1] , giving you the ind value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM