Friendly Code
Friendly Code

Reputation: 1645

PHP - Sorting an array of data rows by price, date ASC, DESC, etc

I have an array of data which contains associative array rows and I would like to sort them by price,date etc. This cannot be done via SQL as these values are not in a database - I simply have a large array with the following example data:

$data[0] = array(
                 'id' => '2',
                 'price' => '400.00',
                 'date' => '2012-05-21',
                 ),
$data[1] = array(
                 'id' => '4',
                 'price' => '660.00',
                 'date' => '2012-02-21',
                 ),
$data[2] = array(
                 'id' => '8',
                 'price' => '690.00',
                 'date' => '2012-01-21',
                 )

etc..................

How can I sort this variable based on a select box such as sort by price ASC/DESC and date ASC/DESC

Sorry if this is simple - I am just so used to doing it via SQL that my mind has gone blank in this case.

Upvotes: 0

Views: 4821

Answers (4)

gcochard
gcochard

Reputation: 11744

You should use usort and define a function which sorts based on the key you want.

Check out http://www.php.net/manual/en/function.usort.php examples 2 and 4.

Upvotes: 3

Sunil Kartikey
Sunil Kartikey

Reputation: 525

Below sample code will sort it by id.

    $capitals = array(
     array(
             'id' => '2',
             'price' => '400.00',
             'date' => '2012-05-21',
             ),
     array(
             'id' => '1',
             'price' => '660.00',
             'date' => '2012-02-21',
             ),
     array(
             'id' => '0',
             'price' => '690.00',
             'date' => '2012-01-21',
             )

       );




  function cmp($a, $b)
  {
     return strcmp($a["id"], $b["id"]);
   }


 usort($capitals, "cmp");

 print_r($capitals);

Upvotes: 0

Kep
Kep

Reputation: 5857

Use usort:

function sortBySubKey(&$array, $key)
{
    return usort($array, create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) return 0; return ($a["'.$key.'"] < $b["'.$key.'"]) ? -1 : 1;'));
}

You should make sure that your array holds valid values in the sense of this arithmetical comparision (<), eg. you should probably pass date as a unix timestamp for this, price as a float and so on...

Upvotes: -1

Vaidotas Strazdas
Vaidotas Strazdas

Reputation: 716

I think you may modify this function: http://php.net/manual/en/function.sort.php#104464

Upvotes: 5

Related Questions