Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top