Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 688
user801347 Avatar asked Jun 23 '11 22:06

user801347


2 Answers

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>';
like image 69
hakre Avatar answered Oct 13 '22 09:10

hakre


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>';
}
like image 29
Andrew Moore Avatar answered Oct 13 '22 11:10

Andrew Moore