Sort array

Hi all! Can you please help me with an array sorting issue? I have an array $products[$fields] where I would like to sort decreasing by $products[‘form_to_comparison’] and maintain all [$fields] key associations. So, the product with the highest form_to_comparison value will be $products[‘form_to_comparison’][0], and other vlues for the same product would be $products[‘name’][0] or $products[‘price’][0]

Thank you!

Maybe this page which shows the results of using Php sorting functions could be helpful:

http://www.johns-jokes.com/downloads/sp-g/jb-sorted/

Edit:
It would also be helpful if you could supply a sample source array and the desired results.

Thanks for the link. My difficulty is that there are arrays within arrays.

Example source:

$products['form_to_comparison'][0] => 2
$products['form_to_comparison'][1] => 10
$products['form_to_comparison'][2] => 5
$products['pid'][0] => 1
$products['pid'][1] => 2
$products['pid'][2] => 3
$products['name'][0] => 'Watch'
$products['name'][1] => 'Band'
$products['name'][2] => 'Bracelet'

Example result:

$products['form_to_comparison'][0] => 10
$products['form_to_comparison'][1] => 5
$products['form_to_comparison'][2] => 2
$products['pid'][0] => 2
$products['pid'][1] => 3
$products['pid'][2] => 1
$products['name'][0] => 'Band'
$products['name'][1] => 'Bracelet'
$products['name'][2] => 'Watch'

What I might try in this case is to create a function call array that loops through the [$fields] and runs the corresponding sort function…

$sortType = array('form_to_comparison'=>'rsort','pid'=>'rsort','name'=>'sort');
foreach ($sortType as $field => $sortFoo){
	  $sortFoo($products[$field]);
}

(btw, I didn’t get what sorting you wised to do in ‘pid’ I assumed it was sort of values from highest to lowest)

hope that helps

Thanks, but I think I’m still not being clear :frowning:

Each field can’t be sorted independently, because each key (e.g. [0]. [1]. [2]…) is associated with a particular product. I’d like form_to_comparison to be sorted descending, and then all of the other fields’ keys need to follow form_to_comparison to be in the same sequence. So whatever has the highest form_to_comparison needs to be $products[‘pid’][0], $products[‘name’][0], etc. There are lots of fields, and pid and name are merely examples.

Sounds like you may be looking for array_multisort

In particular, Example #3

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.