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?

 

Link to comment
Share on other sites

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;
}
Edited by Ch0cu3r
Link to comment
Share on other sites

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;
	}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.