Jump to content

looping json array


hyster
Go to solution Solved by Barand,

Recommended Posts

im trying to loop the array but its throwing an error on the 500020315 saying its unexpected.

echo a single entry works fine but I don't understand why it dosent like the number in the foreach

 

thanks for any help 

$output = json_decode($json, true);

// works fine with single entry
echo $output['data']['500020315']['members']['3']['role']; // needs to be looped

foreach ($output->data->500020315->members as $item)
{

 echo $item->role . '<br>';

}
Link to comment
Share on other sites

this code works fine but id like to sort by the account_name alphabetically.

I have found the sort() function  but the only examples I can find sort from the "1st" level of an array.

 

sort($output) wont work as there is nothing to sort by I need something like

sort($output['data']['500020315']['members']['account_name'])  

 

but when I try to use sort ill get an unexpected foreach

$output = json_decode($json, true);

echo '<table>';

foreach ($output['data']['500020315']['members'] as $item)
{
   echo '<tr><td>'.$item['account_name'] . '</td></tr>';
}
?>
</table>
Link to comment
Share on other sites

$output = array(
'data'=>array(
'500020315'=>array(
'members'=>array(
array('account_name'=>'zebra'),
array('account_name'=>'gazelle'),
array('account_name'=>'chiken'),
array('account_name'=>'antelope')
))));


usort($output['data']['500020315']['members'],function($a, $b) {

    $c = $a['account_name'];
    $d = $b['account_name'];

    if($c == $d) return 0;
    else if($c > $d) return 1;
    else return -1;
});

 

Edited by hansford
Link to comment
Share on other sites

  • Solution

for string fields, just use strcmp() in the function (that's what it's for)

usort($output['data']['500020315']['members'],function($a, $b) {
            return strcmp($a['account_name'], $b['account_name']) ;
});

For numeric sorts, return  $a - $b

 

(To sort DESC, reverse a and b in the comparisons)

  • Like 2
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.