php - 获取多维数组的值
问题描述
我有一个看起来像这样的数组
Array
(
[Product_1] => Array
(
[price] => 123.00
)
[Product_2] => Array
(
[price] => 456.00
)
)
如果可能的话,我想做的是这样的
$arr['Product_1']['price']
然后会打印出 product_1 的价格,如果我这样做了
$arr['Product_2']['price']
它将打印出 product_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'])''
}
解决方案
如果您在循环$arr['Product_2']['price']
内部调用foreach
,PHP 将尝试在实际定义之前访问第二个元素。
dd($arr['Product_2']['price']);
在循环完成数组解析后调用最后一行$products
,警告将不再出现。
希望这可以帮助。
推荐阅读
- php - php错误安装imagick
- c - 将指针类型转换为 &(int*) 和 (int*)& 并将其分配给某个指针变量时有什么区别?
- arrays - 从数组中删除特定字符串
- r - 用R中的组分隔的三个零之前和三个之后的条件替换类别的中位数
- jquery - 为什么 .hover() 不能与 Animate.css 一起使用?
- regex - Elasticsearch 正则表达式没有前进,但正则表达式模式是正确的
- python - 如何在 python 底图中显示印度地图的地区?
- java - 为每个测试用例打开一个新浏览器是一种好习惯吗?(硒,JUnit)
- angular - 检查angular2中对象数组中的重复值
- python - pyodbc:无法执行很长的 sql 语句