简体   繁体   中英

how to sort array in decending order in php using data retrived from an API

im using an API to get data from their server however im trying to sort that data in a descending order. Originally these messages are displayed with the oldest one first and the newest one last, right at the bottom iv used arsort but it only displays the latest message and doesn't display any other previous messages, so just one message shows up

It should be like this.. You need to more arsort() outside of the foreach construct.

    $arr = json_decode($response, true); 
    arsort ($arr['messages']);

    foreach($arr['messages'] as $message)
    { 
    echo ($message['number'])."<br />";echo ($message['message'])."<br />";echo ($message['date'])."<br /><br />"; 
    }

EDIT :

Sorting the date using array_multisort

foreach ($message as $k => $v) {
    $dtorder[$k]  = strtotime($v['date']);
}
array_multisort($dtorder, SORT_DESC, $message);

Your code is interpreted like this:

foreach($arr['messages'] as $message) {
    arsort ($message);
}
echo ($message['number'])."<br />";echo ($message['message'])."<br />";echo ($message['date'])."<br /><br />"; 

because of where you placed your arsort call. Change it to this:

arsort ($message);
foreach($arr['messages'] as $message) {
    echo ($message['number'])."<br />";echo ($message['message'])."<br />";echo ($message['date'])."<br /><br />";    
}

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