Sort php array values!

1

I have a return JSON .

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

Where I use foreach to traverse it!

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

I need to sort the value I get in descending order, not according to $e->name , but $e->donations so I need to display names in descending order according to 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 this?

    
asked by anonymous 03.12.2017 / 23:20

1 answer

2

You can use one of the methods usort and cures , both work in the same way, get array and a compare 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 / a>

Reference

03.12.2017 / 23:47