# Thread: Sort multidimentional array by an array value

1. ## Sort multidimentional array by an array value

Hi folks
Proper brain fart moment here....

Say I have a multidimentional array such as:
PHP Code:
``` \$d = array(     "set1"=>array(         "name"=>"Product 1",         "price"=>"22.00"),     "set2"=>array(         "name"=>"Product 2",         "price"=>"12.00"),     "set3"=>array(         "name"=>"Product 3",         "price"=>"244.00")     );  ```
I need to sort it by price....

help!

2. uasort();

PHP Code:
``` <?php\$d = array(    "set1"=>array(        "name"=>"Product 1",        "price"=>"22.00"),    "set2"=>array(        "name"=>"Product 2",        "price"=>"12.00"),    "set3"=>array(        "name"=>"Product 3",        "price"=>"244.00")    );// sort low to highuasort ( \$d, create_function ( '\$a,\$b', 'return ( \$a["price"] == \$b["price"] ? 0 : ( \$a["price"] < \$b["price"] ? -1 : 1 ) );' ) );print_r ( \$d );// sort high to lowuasort ( \$d, create_function ( '\$a,\$b', 'return ( \$a["price"] == \$b["price"] ? 0 : ( \$a["price"] > \$b["price"] ? -1 : 1 ) );' ) );print_r ( \$d );?> ```

3. nice
Thanks

4. Here's another way, not saying its better, its just that I am swotting up on this in any case ...

PHP Code:
``` \$d = array(    "set1"=>array(        "name"=>"Product 1",        "price"=>"22.00"),    "set2"=>array(        "name"=>"Product 2",        "price"=>"12.00"),    "set3"=>array(        "name"=>"Product 3",        "price"=>"244.00")    ); //reassign the values if "set1" is meaninglessforeach ( \$d as \$k=>\$v ){// offers the possibilty to make sure price is a FLOAT too\$product[ \$v['price'] ] = \$v['name'];  }ksort(\$product) ;// print_r(\$product) ;// gives// Array ( [12.00] => Product 2 [22.00] => Product 1 [244.00] => Product 3 )  ```

5. also nice cups buuuuuuut forgot to mention that there are 6 other value in the array besides name and price

6. typical, do you expect me to read between the lines? (tehe...)

7. Originally Posted by printf
PHP Code:
``` uasort ( \$d, create_function ( '\$a,\$b', 'return ( \$a["price"] == \$b["price"] ? 0 : ( \$a["price"] < \$b["price"] ? -1 : 1 ) );' ) );  ```
This can be expressed much simpler using subtraction:

PHP Code:
``` uasort(\$d, create_function('\$a,\$b',      'return \$a["price"] - \$b["price"];'));  ```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•