Reputation: 111
I have an associative array in PHP that looks like this
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'?
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 --------
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"
}
}
Upvotes: 0
Views: 615
Reputation: 571
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.
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.
Upvotes: 1
Reputation: 893
Below, $a
contains the first element of the nested array and $b
contains the second element.
$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";
}
Upvotes: 0