Jump to content

[SOLVED] I've spent a day trying to figure out how to sort this multidimensional array...


easyedy

Recommended Posts

Hey all I've been banging my head against the wall for nearly a day trying to figure out how to sort this 3 level array. Everything I've tried has just spit out errors at me. Can you guys take a look.

 

Here is a sample what the array outputs:

 

      $result

            (

                [ArrayResult] => Array

                    (

                        [Result] => Array

                            (

                                [0]=> Array

                                    (

                                        [iD] => x432

                                        [Name] => Name Z

                                        [Qty] => 32

 

                                    )

 

                                [1] => Array

                                    (

                                        [iD] => x751

                                        [Name] => Name P

                                        [Qty] => 71

 

                                    )

 

                                  [2] => Array

                                    (

                                        [iD] => x915

                                        [Name] => Name B

                                        [Qty] => 55

 

                                    )

 

                            )

 

 

                    )

              )

 

I'm trying to sort the array by ['Qty'] before my for each and I just can't seem to get it. Any ideas as to what I'm missing... I'm at ends wit. Thanks

 

 sort ($result['ArrayResult']['Result']['Qty']);
      foreach ($result['ArrayResult']['Result'] as $row)  {
      echo $row['Qty']. ' - ' . $row['Name'];
      }

Try this:

<?php
function cmp($a, $b)
{
if($a['Qty'] == $b['Qty'])
{
	return 0;
}

return ($a['Qty'] < $b['Qty']) ? -1 : 1;
}

usort($result['ArrayResult'], 'cmp');
?>

 

I think you need to sort the next level

 

usort($result['ArrayResult']['Result'], 'cmp');

 

Also, FYI, the cmp() function can be reduced to

 

<?php
function cmp($a, $b)
{
       return $a['qty'] - $b['qty'];
}
?>

 

as any -ve, 0, +ve integer result will suffice

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.