Link to home
Start Free TrialLog in
Avatar of Mr_Splash
Mr_Splash

asked on

Sorting an assosiative array

Hi,

I have an array that's structed like the example below. Can anyone tell me how I can order it by the "Fruit" value.
array(
 
  [0] => array("Furniture"=>"Table", "Fruit"=>"Banana","Shoes"=>"Brogues"),
  [1] => array("Furniture"=>"Chair", "Fruit"=>"Apple","Shoes"=>"Wellingtons"),
  [2] => array("Furniture"=>"Bookcase", "Fruit"=>"Guava","Shoes"=>"Trainers"),
  [3] => array("Furniture"=>"Fridge", "Fruit"=>"Orange","Shoes"=>"Sandals")
 
);

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Why is the array structured that way?  Why not structure it so you can order it easily?
Avatar of Mr_Splash
Mr_Splash

ASKER

The data has come from a MySQL database.

If it's not possible like this, how would this be better sructured?
I think we can sort it.  Let me test a script and I will post a sample in a moment.
This example will leave associative indexes in the $new array.  See if it makes sense and please post back here with any question.  Best regards, ~Ray
<?php // RAY_sort_array.php
error_reporting(E_ALL);
echo "<pre>\n"; // READABILITY
 
 
// FROM THE OP
$arr = array(
 
  0 => array("Furniture"=>"Table",    "Fruit"=>"Banana", "Shoes"=>"Brogues"),
  1 => array("Furniture"=>"Chair",    "Fruit"=>"Apple",  "Shoes"=>"Wellingtons"),
  2 => array("Furniture"=>"Bookcase", "Fruit"=>"Guava",  "Shoes"=>"Trainers"),
  3 => array("Furniture"=>"Fridge",   "Fruit"=>"Orange", "Shoes"=>"Sandals")
 
);
 
// VISUALIZE THE INPUT
// var_dump($arr);
 
// COPY THE ARRAY
$new = array();
foreach ($arr as $key => $sub_array)
{
    $fruit = $sub_array["Fruit"];
    $new["$fruit"] = $sub_array;
}
 
// VISUALIZE THE COPY
// var_dump($new);
 
// SORT THE COPY
ksort($new);
 
// VISUALIZE THE SORTED COPY
var_dump($new);

Open in new window

Thank you Ray,

However, this won't work if two sub arrays have the same fruit. Sorry I should have made that clearer.
"Sorry I should have made that clearer."

Yes, and if that was something you needed, it would have been good to post an example that showed what you needed!  

What would be the criteria for two "Guava" - which should come first?  These are app development and business logic choices that you need to clear up before you write the code.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Perfect, the array is already in its subsidiary order. This was a basic example, in the app it's already in Surname order.
Excellent!  Thanks for the points - it's a good question.

If you wanted to sort in (for example) Fruit + Shoes order you might make that adjustment on lines 23 and 24 as you construct the $newkey variable.

Best,  ~Ray