# Sorting array of arrays problem

Page 1 of 1

## 1 Replies - 346 Views - Last Post: 07 February 2013 - 12:19 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=311528&amp;s=b4d87eaa7ed37c7e51361a44a20794f4&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 el_pancho

Reputation: -1
• 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

• Programming Theoretician

Reputation: 4625
• Posts: 12,677
• 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