1

I have an N amount of products with an n amount of properties.

How exactly could I use a for each inside a for each to get the properties of each product? Is it by storing an array in an array or something?

Thanks

2
  • Can you be more clear? N products with n properties each or having various amount of properties? Commented Aug 2, 2011 at 5:20
  • Do you mean that you have a main array containing arrays that represent products? Such as array(array("name"=>"cake", "cost"=>3.8),array("name"=>"cookie", "cost"=>1.75)); Commented Aug 2, 2011 at 5:21

2 Answers 2

5
$products = array(
    array('name' => 'Product 1', 'color' => 'red', 'size' => 'large'),
    array('name' => 'Product 2', 'color' => 'blue', 'size' => 'medium'),
    array('name' => 'Product 3', 'color' => 'green', 'size' => 'small')
);

foreach ($products as $product) {
  foreach ($product as $property => $value) {
    echo $property . " = " . $value . ",";
  }
  echo "<br />";
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I assumed was meant also, +1
0

If remember well you could also randomly access them using something like

echo $products['name']['size'];

or

$products['name']['size'] = 5;

if that's what you need;

For a shopping cart for example you could use for product - quantity

$products['apple']['quantity']++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.