Reputation: 569
I need to access the specific key/value
of associative array as variables using foreach
loop. Getting key/value
pairs of all data in the array
is not a problem. The problem is with getting a specific key/value
. Take the code below for example
<?php
$data = [
'person1' =>
[
'id' => 101,
'firstName' => 'John',
'LastName' => 'Smith'
],
'person2' =>
[
'id' => 102,
'firstName' => 'Mary',
'LastName' => 'Smart'
]
];
I can get key/value
pairs of all data in the array
by the code below:
foreach($data as $firstKey => $firstValue){
foreach ($firstValue as $secondKey => $secondValue) {
echo $secondKey. ": ". $secondValue . "<br />";
}
}
The above code is not exactly what I want.
I want to get specific key/value
for example, I want to get only the key/value of only the id
s.
So I tried something like this:
$specificId = null;
foreach($data as $firstKey => $firstValue){
foreach ($firstValue as $secondKey => $secondValue) {
if($secondKey == 'id'){ // using if statement to get key/value pair of person's id
$specificId = $secondValue; //storing the specific ids as variable
echo $secondKey . ": ". $specificId . "<br>";
}
}
}
?>
The above code seems to work but if I also want to get key/value
for only firstName
, then, I have to write another if
statement.
I will end up writing so many if
statements in the foreach
loop. Do you know another way I can write lesser code to get specific key/value
pairs?
There are many similar questions like mine but the answer I am looking for is not the objective of any of those questions.
Upvotes: 1
Views: 6899
Reputation: 101
To access specific key values you need to convert the array to Json and access it just like a normal object.
$data = [
'person1' =>
[
'id' => 101,
'firstName' => 'John',
'LastName' => 'Smith'
],
'person2' =>
[
'id' => 102,
'firstName' => 'Mary',
'LastName' => 'Smart'
]
];
$obj = json_decode(json_encode($data));
//to access key=values directly
echo $obj->person1->firstname;
//to access all firstname only
foreach($obj as $o){
echo $o->firstName;
}
Upvotes: 0
Reputation: 171
foreach($data as $firstKey => $firstValue) {
echo array_keys($firstValue, $firstValue['id'])[0].': '.$firstValue['id'].'</br>';
echo array_keys($firstValue, $firstValue['firstName'])[0].': '.$firstValue['firstName'].'</br>';
}
you can just call the associative array key from the array
This outputs key and values
Upvotes: 3