Jump to content

Fun with arrays! Distribute an array into groups/sets.


poleposters

Recommended Posts

Hi,

 

I need some help getting my head around arrays.

 

I have a basket of fruit:

 

$basket=("Apple","$Orange","$Banana","$Banana","$Peach","$Apple","$Banana","$Orange","$Apple");

 

I want to distribute and share this basket of fruit into bowls, such that each bowl contains the following:

 

$bowl=("$Apple",$Orange,"$Banana","$Banana")

 

ie. One Apple, One Orange & Two Bananas.

 

I can't seem to figure out how to do it.

 

Thanks in advance.

 

You only have enough fruit for one complete bowl.  What do you want to do with the extra items?  After the first bowl you will only have one banana , so do you want a second bowl with an apple an orange and a banana and then a third with only an apple?

<?php
$basket = array('$Apple','$Orange','$Banana','$Banana','$Peach','$Apple','$Banana','$Orange','$Apple');
$order  = array('$Apple','$Orange','$Banana','$Banana');

function filter($arrSort, $arrOrder)
{
   $arrSort = array_unique($arrSort);

   foreach($arrSort as $val)
   {
      if (in_array($val, $arrOrder))
      {
         return true;
      }
      else
      {
         continue;
      }
   }
   
   return false;
}


function sortFruit(&$basket, $order)
{
   $bowl  = array();
   $index = 0;

   while(filter($basket, $order))
   {
      for ($i = 0; $i < count($order); $i++)
      {
         if ( in_array($order[$i], $basket) )
         {
            $bowl[$index][] = $order[$i];
            unset($basket[array_search($order[$i], $basket)]);
         }
         else
         {
            $bowl[$index][] = 'NULL';
         }
      }
      
      $index++;
   }
   
   return $bowl;
   
}
echo 'Basket:<br >';
echo '<pre>' . print_r($basket, true) . '</pre><br ><br >';

echo 'Order:<br >';
echo '<pre>' . print_r($order, true) . '</pre><br ><br >';

$bowl = sortFruit($basket, $order);

echo 'Ordered Basket(s):<br >';
echo '<pre>' . print_r($bowl, true) . '</pre><br ><br >';

?>

 

Long winded but does the trick. ;)

After a day of studying the code above I've finally figured out how it all works. But now I've encountered a new problem.

 

How could I modify the code to allow me to store some information about each piece of fruit?

 

e.g red apple, green apple, yellow banana

 

This would not affect the way the fruit is sorted into bowls. A red or green apple could go into the bowl interchangeably. I would just like to be able to access the bowl array to determine whether the apple is green or red.

 

Thanks!

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.