开发者

How do I have a more advanced array?

Basically I currently put a bunch of values into an array like so:

$flavors = array('Original','Cherry','Chocolate','Raspberry','Mango');

and from this I might execute a foreach like so:

    foreach($flavors as $flav) {

    echo doSomething($flav);

}

This all works a treat, until I get to the next stage of my learning which is to perhaps put 2 variables into doSomething().

For example, say I want to include the ingredients of Cherry e.g

 echo doSomething($flav, $ingredient_of_this_flav);

I'm not sure if there is any way to go about doing this... I imagine I might need a second array entirely where I use the values above as my keys? e.g

$ingredients = array('Original' => 'boring stuff', 'Cherry' => 'cherries and开发者_JAVA百科 other stuff') etc

And then I would doSomething() like so

    foreach($flavors as $flav) {

    echo doSomething($flav, $ingredients[$flav]);

}

I suppose I should go try this now. Is this the best approach or is there a better way to go about this? Ideally I would just have the one array not have to set $flavors and $ingredients.

Thanks for your time.


Arrays in php are associative, as you've noticed. And if I understand correctly, you're looking for the syntax to loop through each key/value pair?

foreach($ingredients as $flav => $ingredient) {
  echo doSomething($flag, $ingredient);
}

Is this what you're looking for?

If you're looking to have complex values for each key, than you might want to look into objects, or the more brutal version, arrays of arrays.

$ingredients = array('Cherry' => array('Cherries', 'Other stuff'));

And your $ingredient in the loop above will be an array.


You can foreach over the keys and values of an array.

   foreach ($ingredients as $flav => $ingredients) 
   {
       echo doSomething($flav, $ingredients);
   }


I would use an associative array (aka hash table) with a flavor => ingredients approach. Something like this:

$flavors = array ('Cherry' => array('stuff1', 'stuff2'), 
                  'Mango' => array('stuff1', 'stuff3'));

echo $flavors['Cherry'][0]; // stuff1

foreach($flavors as $flavor => $ingredients)
{
  print $flavor;
  // $ingredients is an array so we need to loop through it
  foreach($ingredients as $ingredient)
  {
    print $ingredient;
  }
}

This is known as a nested loop and will print the flavor and each ingredient.


You are nearly there. I would set the array to be something like:

$ingredients = array('Original' => array('boring stuff', 'boring stuff2'), 'Cherry' => array('cherries', 'other stuff'));

And then loop as follows:

foreach($flavors as $flav => $ingredient) {

        echo doSomething($flav, $ingredient);

}

Of course, it all depends on what you do in "doSomething()"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜