Reputation: 1459
I have an array in PHP structured like below. If I return the 'StateID' from a REST call, how can I use the ID to get the abbreviation and state name for that ID? For example an ID of '1' would return an abbreviation of Name = Alabama and Abbreviation = AL..
Array:
array(1) { ["StateList"]=> array(50)
{ [0]=> array(3)
{ ["StateID"]=> int(1) ["Name"]=> string(7) "Alabama" ["Abbreviation"]=> string(2) "AL" }
[1]=> array(3)
{ ["StateID"]=> int(2) ["Name"]=> string(6) "Alaska" ["Abbreviation"]=> string(2) "AK" }....
Upvotes: 0
Views: 318
Reputation: 2851
$id = 1; // Searched ID
foreach ($array['StateList'] as $key => $value) {
if ($value['StateID'] == $id) {
echo $value['Name'];
echo $value['Abbreviation'];
break;
}
}
Hope it helps, just a matter of one simple loop.
PS. This is a linear solution. Of course You can make a function out of it:
function FindId($array, $id) {
foreach ($array as $key => $value) {
if ($value['StateID'] == $id) {
return $value;
break;
}
}
return false;
}
$result = FindId($array['StateList'], 1);
print_r($result);
Upvotes: 3