poleposters Posted May 16, 2010 Share Posted May 16, 2010 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 Quote Link to comment Share on other sites More sharing options...
dirkers Posted May 16, 2010 Share Posted May 16, 2010 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 Quote Link to comment Share on other sites More sharing options...
poleposters Posted May 18, 2010 Author Share Posted May 18, 2010 Thank you so much.It works great! Quote Link to comment Share on other sites More sharing options...
poleposters Posted June 15, 2010 Author Share Posted June 15, 2010 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! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.