简体   繁体   English

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

[英]How to get a value of associative array in php

I have an associative array in PHP that looks like this我在 PHP 中有一个关联数组,看起来像这样

input array输入数组

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

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

    )

How do I access the value for 'id' and 'price'?如何访问“id”和“price”的值?

I've tried我试过了

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>'; 
}

they all return only price value not id and throwing error Notice: Undefined index: id它们都只返回价格值而不是 id 并抛出错误注意:未定义索引:id

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

expected result预期结果

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"
  }
}

Try this, but in a new fresh file试试这个,但在一个新的新文件中

$final_atas = [
    [
        'id' => 11304,
        'price' => 5,
    ],
    [
        'id' => 1234,
        'price' => 10
    ]
];

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>'; 
}

This will most likely work, I copied the same foreach loop you provided.这很可能会起作用,我复制了您提供的相同 foreach 循环。

I believe that you are using an SQL query to get the data, in which case, please update the question with the query you are trying and the table structure in database.我相信您正在使用 SQL 查询来获取数据,在这种情况下,请使用您正在尝试的查询和数据库中的表结构更新问题。

Below, $a contains the first element of the nested array and $b contains the second element.下面, $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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM