Jump to content

sorting many arrays by another array


fohanlon

Recommended Posts

Help,

I have 7 arrays all the same size:

$plans = array();
$supplier = array();
$plan_name = array();
$add_on = array();
$hosp_cover = array();
$excess = array();
$plancost = array();

I need to be able to sort the plancost array asc i.e. this contains a costing from lowest to highest. However I require the contents of each of the other arrays to be sorted to match the sorted positions of the plancost array.

I guess as the plancosts arrays sorts it sorts the values at the indexed entries in the other arrays to the sorted position. Hope you understand what I mean.

I tried looking into the sort function and the array_multisort function on php help online manuals but don't think they will slove my problem.

Thanks

Fergal.
Link to comment
https://forums.phpfreaks.com/topic/5057-sorting-many-arrays-by-another-array/
Share on other sites

array_multisort

[code]$plans = array(2,3,1);
$supplier = array('sa','sb','sc');
$plan_name = array('pa','pb','pc');
$add_on = array('aa','ab','ac');
$hosp_cover = array('ha','hb','hc');
$excess = array('xa','xb','xc');
$plancost = array('ca','cb','cc');

array_multisort ($plans, $supplier, $plan_name, $add_on, $hosp_cover, $excess, $plancost);

echo '<pre>', print_r ($plans, true), '</pre>';
echo '<pre>', print_r ($supplier, true), '</pre>';
echo '<pre>', print_r ($plan_name, true), '</pre>';
echo '<pre>', print_r ($add_on, true), '</pre>';
echo '<pre>', print_r ($hosp_cover, true), '</pre>';
echo '<pre>', print_r ($excess, true), '</pre>';
echo '<pre>', print_r ($plancost, true), '</pre>';[/code]
Make sure the array you want to sort on is listed first, and be careful to choose numeric sort or string sort. String sort is the default.

[code]$plancost = array(2,3,1);
$supplier = array('sa','sb','sc');
$plan_name = array('pa','pb','pc');
$add_on = array('aa','ab','ac');
$hosp_cover = array('ha','hb','hc');
$excess = array('xa','xb','xc');
$plans = array('ca','cb','cc');

array_multisort ($plancost, SORT_NUMERIC, SORT_ASC,
$supplier, $plan_name, $add_on, $hosp_cover, $excess, $plans);

echo '<pre>', print_r ($plans, true), '</pre>';
echo '<pre>', print_r ($supplier, true), '</pre>';
echo '<pre>', print_r ($plan_name, true), '</pre>';
echo '<pre>', print_r ($add_on, true), '</pre>';
echo '<pre>', print_r ($hosp_cover, true), '</pre>';
echo '<pre>', print_r ($excess, true), '</pre>';
echo '<pre>', print_r ($plancost, true), '</pre>';[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.