0

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" }....
2
  • Loop through the array to find the entry you need. Commented Jul 25, 2014 at 19:52
  • echo array_reduce($arr, function ($abbr, $state) { return $abbr ?: ($state['StateID'] == 1 ? $state['Abbreviation'] : null); }) - just because. Commented Jul 25, 2014 at 19:57

1 Answer 1

3
$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);
Sign up to request clarification or add additional context in comments.

2 Comments

Just had to change $array to $array['StateList'], but your answer was 90% of the way there. Thanks!
Ah, sorry, my fault! Thx for accept! I will correct it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.