开发者

Array of array of values in php?

开发者 https://www.devze.com 2023-03-24 18:34 出处:网络
I have an N amount o开发者_开发技巧f 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

I have an N amount o开发者_开发技巧f 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


$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 />";
}


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']++;
0

精彩评论

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