简体   繁体   中英

Sort an array according to the value in php

Here is my array . I want to sort the array according the value of each key Input array:-

Array
(
    [location_classroom] => 209
    [location_daily_pe] => 1
    [location_hallways] => 3
    [location_playground] => 93
    [location_shade_area] => 26
    [location_specialist] => 8
    [location_toilet] => 3
    [location_others] => 27
    [location_others_info] => 0
)

Output array:-

Array
(
    [location_others_info] => 0
    [location_daily_pe] => 1
    [location_hallways] => 3
    [location_toilet] => 3
    [location_specialist] => 8
    [location_shade_area] => 26
    [location_playground] => 93
    [location_classroom] => 209
    [location_others] => 27

)

Indeed you should use asort() :

$arr = [
    'location_classroom' => 209,
    'location_daily_pe' => 1,
    'location_hallways' => 3,
    'location_playground' => 93,
    'location_shade_area' => 26,
    'location_specialist' => 8,
    'location_toilet' => 3,
    'location_others' => 27,
    'location_others_info' => 0
];

asort($arr);
# but you can't print the output of the sorting - it'll give you nothing meaningful (boolean)
# you should print the sorted array itself
print_r($arr);

OUTPUT

 Array
(
    [location_others_info] => 0
    [location_daily_pe] => 1
    [location_toilet] => 3
    [location_hallways] => 3
    [location_specialist] => 8
    [location_shade_area] => 26
    [location_others] => 27
    [location_playground] => 93
    [location_classroom] => 209
)

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