简体   繁体   中英

PHP: How reverse a JSON array

Can someone help me with some PHP please.

The original code ~works, but the output is in the wrong order. So I need to REVERSE the sequence/order of the JSON array.

But when I try to reverse the sequence with PHP (extract) code below:

$json = file_get_contents($url,0,null,null); 
$tmp = json_decode($json, true);    // using a temp variable for testing
$result = array_reverse($tmp);      //  <--new line to reverse the arrray

foreach ($result['data'] as $event) {
    echo '<div>'.$event['name'].'</div>';

It doesnt reverse the output sequence.

What am I doing wrong? Is there another/better way?

PS - I can do it in Javascript, but I need to do it server-side.

You do the reversion, but on the wrong field. You want to reverse the data fields instead of the array:

$json = file_get_contents($url,0,null,null); 
$tmp = json_decode($json, true);    // using a temp variable for testing
$result = $tmp;
$result['data'] = array_reverse($result['data']);

foreach ($result['data'] as $event) {
    echo '<div>'.$event['name'].'</div>';

You need to reverse the content of the $tmp['data'] array, not $tmp itself.

$json = file_get_contents($url); 
$tmp = json_decode($json, true);
$result = array_reverse($tmp['data']);

unset($tmp);

foreach ($result as $event) {
  echo '<div>'.$event['name'].'</div>';
}

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