我试图弄清楚如何从PHP数组内部抓取数据,即使我不知道关于数组的一切。例如,我有这个:
$currentprice = $product_info['products'][5]['price'];
但我不知道[5]会有什么。下面是我正在使用的一个实际数组的示例,它每次都会根据添加到商店购物车中的产品而更改:
Array (
[5] => Array (
[name] => Product 1
[price] => $0.07
[quantity] => 10
)
[12] => Array (
[name] => Product 2
[price] => $0.26
[quantity] => 5 )
[14] => Array (
[name] => $10 fee
[price] => 10
[quantity] => 1
[options] => Array ( ) )
[17] => Array (
[name] => Additional Fee
[price] => $60.00
[quantity] => 5 )
)
是否可以这样写:
$currentprice = $product_info['products'][*]['price'];
其中[*]将充当通配符并查看第二个嵌套数组的内部以查看价格是多少?
只有foreach循环可以在这里使用,因为键不是你知道的东西,它是由PHP生成的。foreach的用法如下:
<?php
foreach( $product_info as $product ) {
echo $product[ 'price' ];
}