Jump to content

sorting an associative array by first key


AdRock

Recommended Posts

I have an array which is pulled from a database like this:

array(3) {
[0]=>
array(2) {
["carrier"]=>
string(10) "Royal Mail"
["consignment"]=>
string(2) "RM"
}
[1]=>
array(2) {
["carrier"]=>
string(5) "FedEx"
["consignment"]=>
string( "31290238"
}
[2]=>
array(2) {
["carrier"]=>
string(3) "TNT"
["consignment"]=>
string(11) "01549957430"
[3]=>
array(2) {
["carrier"]=>
string(3) "TNT"
["consignment"]=>
string(11) "01547847430"
}
}

What I would like to do is sort that array so it's sorted by the 'carrier' key and the 'carrier' key should be echoed out only once if more than 1 row exists but still show the value like this:

 

Royal Mail: Your consignment number is: RM
FedEx: Your consignment number is: 31290238
TNT: Your consignment number is: 01549957430

                                                      01547847430

 

 

How can I achieve this with my code?

 

$myarray = array();


foreach($rows as $row) {


$consignment = $row['consignment_number'];


//do something
if ($consignment == 'RM') {


// despatched by royal mail
$myarray[] = array('carrier'=> 'Royal Mail', 'consignment' => $consignment);
}
elseif ( ctype_digit($consignment) && (strlen($consignment) ==  ) {


// going by FedEx?
$myarray[] = array('carrier'=> 'FedEx', 'consignment' => $consignment);


}
elseif ( ctype_digit($consignment) && (strlen($consignment) == 11) ) {


// going by TNT?
$myarray[] = array('carrier'=> 'TNT', 'consignment' => $consignment);
}
}


echo '<pre>';var_dump($myarray);echo '</pre>';
echo 'Your order has been despatched by: <br />';


$i=0;
foreach ($myarray as $key => $value) {
if(in_array($myarray[0]['carrier'], $allowed)) {


if(!empty($myarray[$i]['carrier'])) {


echo $myarray[$i]['carrier'].': Your consignment number is: '.$myarray[$i]['consignment'].'<br />';


}
$i++;
}
}

Also what happened to the code formatting we used to have ages ago.  How am i supposed to indent the code to make it readable now?

 

Simplify your $myarray.

 

Set the carrier as the key for the array. then you can assign the consignments for that carrier using $myarray[ $carrier ]['consignemts'][] = $consignment;

 

You'll get an array like

Array (
    [Royal Mail] => Array(
         [consignments] = Array(
               [0] => 'consignment number 1',
               [1] => 'consignment number 2',
               ... etc ...
         )
    ),
    [FEDEX] => Array(
         [consignments] = Array(
               [0] => 'consignment number 1',
               ... etc ...
         )
    ),
    [TNT] => Array(
         [consignments] = Array(
               [0] => 'consignment number 1',
               [1] => 'consignment number 2',
               [2] => 'consignment number 3',
               ... etc ...
         )
    )
)

Then you can easily display the carriers consignments using a simple foreach

foreach($carriers as $carrier => $consignments)
{
    echo $carrier . ': Your consignments are: ' . implode(',', $consignments);
}

Code to build the carriers consignments

$carriers = array();
foreach($rows as $row)
{
    $consignment = $row['consignment_number'];

    //do something
    if ($consignment == 'RM')
    {
        $carrier = 'Royal Mail';
    }
    elseif ( ctype_digit($consignment) && (strlen($consignment) ==  )
    {
        $carrier = 'Fedex';
    }
    elseif ( ctype_digit($consignment) && (strlen($consignment) == 11) )
    {
        $carrier = 'TNT';
    }

    // use carrier as key, append consignment to consignments sub array
    $carriers[ $carrier ]['consignments'][] = $consignment;
}

try using this function

function sort_array($array, $key, $order)
	{
		if ($order=="DESC")
			$or="arsort";
		else
			$or="asort";
		for ($i = 0; $i < sizeof($array); $i++) 
		{
			$sort_values[$i] = $array[$i][$key];
		} 
		$or($sort_values);
		reset ($sort_values);
		while (list ($arr_key, $arr_val) = each ($sort_values)) 
		{
			$sorted_arr[] = $array[$arr_key];
		}
		return $sorted_arr;
	}

You can use a custom sort function

function mysort($a,$b) { return strcmp($a['carrier'], $b['carrier']); }
 
usort(myarray, 'mysort');

or you can just sort it normally

sort(myarray);

By default, a 2 dim array should sort on the arrays' first elements.

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.