首页 > 解决方案 > 获取多维数组的值

问题描述

我有一个看起来像这样的数组

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'])''
}

标签: php

解决方案


如果您在循环$arr['Product_2']['price']内部调用foreach,PHP 将尝试在实际定义之前访问第二个元素。

dd($arr['Product_2']['price']);在循环完成数组解析后调用最后一行$products,警告将不再出现。

希望这可以帮助。


推荐阅读