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

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

  • 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!

 

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.