如何在php中获取关联数组的值

问题描述 投票:0回答:1

我在PHP中有一个关联数组,看起来像这样

输入数组

 Array
    (
        [0] => Array
            (
                [id] => 11304
                [price] => 5
            )

        [1] => Array
            (
                [id] => 1234
                [price] => 10
            )

    )

我如何访问'id'和'price'的值?

我已经尝试过

foreach ($final_atas as $key =>$value) {
    echo 'key ----------'.$key.'<br>'; // output 0 and 1
    echo 'price ----------'.$value['price'].'<br>'; // output 5 and 10
    echo 'price ----------'.$value['id'].'<br>';//getting error undefined index id
    echo '<pre>';
    print_r($value);
    echo '</pre>'; 
}

它们都只返回价格值而不是id和抛出错误注意:未定义的索引:id

id --------
price -------- 5
id --------
price -------- 10
Array
(
    [id] => 11304
    [price] => 5
)
Array
(
    [id] => 12034
    [price] => 10
)

预期结果

id --------  11304
price -------- 5
id --------   1234
price -------- 10

var_dump

array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    string(5) "11304"
    ["price"]=>
    string(1) "5"
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(4) "1234"
    ["price"]=>
    string(2) "10"
  }
}
php multidimensional-array
1个回答
0
投票

下面,$a包含嵌套数组的第一个元素,$b包含第二个元素。

$array = [
    [1, 2],
    [3, 4],
];

foreach ($array as list($a, $b)) {
    // $a contains the first element of the nested array,
    // and $b contains the second element.
    echo "A: $a; B: $b\n";
}
© www.soinside.com 2019 - 2024. All rights reserved.