Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I have a form where I'm creating a number of item arrays:

<input type="hidden" value="Full/Double Mattress" name="pickup1-dropoff1Items[1][0]">
<input type="text" name="pickup1-dropoff1Items[1][1]">
<input type="hidden" value="20" name="pickup1-dropoff1Items[1][2]">
<input type="hidden" value="FMat" name="pickup1-dropoff1Items[1][3]">
<input type="hidden" value="1" name="pickup1-dropoff1Items[1][4]">

so the structure is basically:

array(
    array('title', quantity, price, 'shorthand', order),
    array('title', quantity, price, 'shorthand', order)
)

etc...

I'm getting this information using PHP and sending it in an email. I can get one of these arrays like so:

$pickup1_dropoff1Items = $_POST['pickup1-dropoff1Items'];

I would like to sort the arrays in $pickup1_dropoff1Items by the 'order' number (i.e. index #4, i.e. $pickup1-dropoff1Items[i][4]) in each of those arrays.

Can this be done using PHP ksort()? Does anyone have any idea how to sort an array like this using PHP?

Thanks!

share|improve this question

marked as duplicate by Felix Kling, Fabio, Jeremy J Starcher, Rubens, Gian Jun 17 '13 at 0:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

up vote 1 down vote accepted

It's not tested but I think this will do what you need:

// first create a new array of just the order numbers 
// in the same order as the original array
$orders_index = array();
foreach( $pickup1_dropoff1Items as $item ) {
  $orders_index[] = $item[4];
}

// then use a sort of the orders array to sort the original
// array at the same time (without needing to look at the 
// contents of the original)
array_multisort( $orders_index, $pickup1_dropoff1Items );

This is essentially example 1 here: http://www.php.net/manual/en/function.array-multisort.php but our $ar2 is an array of arrays instead of an array of single values. Also if you need more control over the sort you'll see examples of options you can use at that URL: just add them to the list of arguments for array_multisort.

share|improve this answer
    
$orders_index = array(); not $orders_index = []; –  j-man86 Jun 15 '13 at 21:19
    
Make that correction and I'll mark it right! –  j-man86 Jun 15 '13 at 21:26
    
I think someone already made it for me, thanks :) –  Skrivener Jun 15 '13 at 21:58

For sorting complex arrays like this, you can use something like usort() which "sorts an array by values using a user-defined comparison function".

See the example on php.net for more information.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.