Jump to content

How do I sort and print an array into groups according to value?


poleposters

Recommended Posts

Hi I have a multidimensional array.

 

The first key is the name of the product and the second is the delivery method.

 

Stuff | Truck

Widgets | Courier

Thingies | Post

Doovas | Truck

 

I want to creats a list like so.

 

Your Stuff and Doovas will be delivered by truck

Your Widgets will be delivered by Courier

Your Thingies will be delivered by Post

 

Is there a way to sort the array into goups according to one of the keys?

 

Thanks

Link to comment
Share on other sites

How about flipping the array while making the values arrays themselves, like so:

 

<?php

// original array
$ar = array('Stuff'    => 'Truck',
            'Widgets'  => 'Courier',
            'Thingies' => 'Post',
            'Doovas'   => 'Truck');

// initializing new array
$ar2 = array();

// flip key-value pairs
// and stack values as needed
foreach ($ar as $key => $val) {
    if (array_key_exists($val, $ar2)) {
        $ar2[$val][] = $key;
    } else {
        $ar2[$val] = array($key);
    }
}

// output
foreach ($ar2 as $transportMethod => $product) {
    echo "Your " . implode(' and ', $product) . " will be delivered by $transportMethod\n";
}

?>

 

This will output:

Your Stuff and Doovas will be delivered by Truck

Your Widgets will be delivered by Courier

Your Thingies will be delivered by Post

Link to comment
Share on other sites

  • 4 weeks later...

Whoops!

 

I've run into some trouble. I've changed the way I create the array and I can't seem to get it to work.

 

I'm still getting my head around arrays and its still a bit confusing.

 

I'm retrieving records from a database to create the array.

 

Heres a snapshot of how the array is created.

while($select=mysql_fetch_array($result))
	{
	$arr[]=array($select['product'],$select['despatch_method']);
	}

 

If the above solution can be modified to suit the way I create the array that would be great.

 

Thank you!

 

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.