1 Replies - 292 Views - Last Post: 07 February 2013 - 12:19 PM Rate Topic: -----

#1 el_pancho  Icon User is offline

  • D.I.C Head

Reputation: -1
  • View blog
  • Posts: 88
  • Joined: 26-April 12

Sorting array of arrays problem

Posted 07 February 2013 - 12:08 PM

hi guys

i need to sort an array of products that has another array of categories inside,
something like


$prod = array();
$data = array();
$cat  = array();
$n = 0;

// $qr is a returned sql query response

 while($ln = mysql_fetch_array($qr))
{
$data['id'] = $ln['product_id'];
$data['name'] = $ln['product_name'];
$data['cat'] = $ln['product_category'];

$prod[$n] = $data;
$n++;

}

return $prod;




now i have to sort this $prod array by categories without making a new sql query, how do i do that?

Is This A Good Question/Topic? 0
  • +

Replies To: Sorting array of arrays problem

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4400
  • View blog
  • Posts: 12,257
  • Joined: 18-April 07

Re: Sorting array of arrays problem

Posted 07 February 2013 - 12:19 PM

Well one way you could do it is to use the usort() function. Pass it the prod array, then write a function which takes two parameters (which each itself is an array) and then you can do comparisons on the category item of each.

I recommend this way because it would then give you really flexible control of how each of the arrays in the prod array can be compared against one another.

So to simplify this imagine you have a list of products in your prod array and you use this usort() function. $prod[0] and $prod[1] will be passed to the function you define. We will call them $a and $b inside the function. You may have something like...

if ($a['category'] > $b['category']) return 1;
else { return -1; }



If the category of $a is greater than $b's category it will tell usort() to switch $prod[0] and $prod[1].

Hope you get the idea. :)

This post has been edited by Martyr2: 07 February 2013 - 12:19 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1