0

I want to sort a multidimensional array in PHP, based on one of its value.

For example

$shop = array( array("rose", 3 , 'rr'),
               array("daisy", 1 , 'dd'),
               array("orchid", 2 , 'oo') 
             );

I want to sort this array based on 3,1,2 . i.e I want to sort this array in to

$shop = array( array("daisy", 1 , 'dd'),
               array("orchid", 2 , 'oo'),
               array("rose", 3 , 'rr')
             );

Please any one help me! Is there are is any function in PHP to do this?

Saritha
  • 1,917
  • 5
  • 18
  • 23
  • possible duplicate of [Sort php multidimensional array by sub-value](http://stackoverflow.com/questions/4508145/sort-php-multidimensional-array-by-sub-value) – Shakti Singh Apr 05 '11 at 12:19

3 Answers3

1

You need usort() http://ru2.php.net/manual/en/function.usort.php

Emmerman
  • 2,381
  • 15
  • 9
0

It is not VERY correct but you may get a clue form asort function

<?php asort($shop)?>
Igor
  • 2,553
  • 6
  • 23
  • 36
0

Sorting multi-dimensional array (using array_multisort)

$ar = array(
       array("10", 11, 100, 100, "a"),
       array(   1,  2, "2",   3,   1)
      );
array_multisort($ar[0], SORT_ASC, SORT_STRING,
                $ar[1], SORT_NUMERIC, SORT_DESC);
var_dump($ar);

In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order).

array(2) {
  [0]=> array(5) {
    [0]=> string(2) "10"
    [1]=> int(100)
    [2]=> int(100)
    [3]=> int(11)
    [4]=> string(1) "a"
  }
  [1]=> array(5) {
    [0]=> int(1)
    [1]=> int(3)
    [2]=> string(1) "2"
    [3]=> int(2)
    [4]=> int(1)
  }
}

Source: http://php.net/manual/en/function.array-multisort.php

Mukesh Chapagain
  • 24,139
  • 14
  • 114
  • 117