我得到了一个像这样的数组
Array
(
[Product_1] => Array
(
[price] => 123.00
)
[Product_2] => Array
(
[price] => 456.00
)
)
如果可能的话,我想做的是这样的事情
$arr['Product_1']['price']
然后打印出product_1的价格,如果我这样做了
$arr['Product_2']['price']
它将打印出产品2的价格。
我之所以想做这样的事情,是为了让我可以比较产品1和产品2,因为我需要做的是抓住它们的价格,并相互比较。
现在发生的事情是即使我做了
$arr['Product_2']['price']
我得到了这个错误
Undefined index: Product_2
这是我的代码
$arr = [];
foreach($products as $productCode => $product)
{
$arr[$productCode] = ([
'price' => $product->price
]);
dd($arr['Product_2']['price'])''
}
如果在foreach
循环中调用$arr['product_2]['price]
,PHP将尝试在实际定义第二个元素之前访问它。
在循环完成对$products
数组的解析之后,调用最后一行dd($arr['product_2']['price']);
,警告将不再出现。
希望这能帮上忙。