Sort php array values!

Asked

Viewed 768 times

1

I have a comeback JSON.

"members": [
        {
            "name": "Drogo",
            "role": 3,
            "donations": 278,

Where do I use the foreach to travel it!

foreach ( $CMAMBERS as $e )
    {
       echo "nome: $e->name<br>";
    }

I need to sort the amount I receive in descending order, not according to the $e->name, but rather the $e->donations then I need to display the names in descending order according to the array donations

So if I have the following values:

"Name": "Drogo"
"donations": "150"

"Name": "FoX"
"donations": "350"

"Name": "TRE"
"donations": "250"

I should print like this:

"FoX"
"TRE"
"Drogo"

How can I do that?

1 answer

2


You can use one of the methods usort and uasort, both work the same way, receives the array and a comparison function.

$dados = [
  [
    'nome' => 'Drogo',
    'donations' => 150
  ],
  [
    'nome' => 'FoX',
    'donations' => 350
  ],
  [
    'nome' => 'TRE',
    'donations' => 250
  ]
];

uasort($dados, function ($a, $b) {
  return $a['donations'] < $b['donations'];
});

foreach ( $dados as $e )
{
  echo "nome: " . $e['nome'] . "\n";
}

See working uasort and usort

Reference

  • I believe it is not possible to use inside the foreach, I need to use inside it!

  • Make the ordination before the foreach. I updated the answer and the working examples.

  • Ah, yes of course... Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.