0

I have an array:

"city": [
{
 "kind": "qpxexpress#cityData",
 "code": "CHI",
 "name": "Chicago"
},
{
 "kind": "qpxexpress#cityData",
 "code": "LAX",
 "name": "Los Angeles"
},
{
 "kind": "qpxexpress#cityData",
 "code": "YMQ",
 "name": "Montreal"
},
{
 "kind": "qpxexpress#cityData",
 "code": "YOW",
 "name": "Ottawa"
},
{
 "kind": "qpxexpress#cityData",
 "code": "YVR",
 "name": "Vancouver"
}

]

It's complete path is: array->trips->data->city What I want to do is get the "name" from the array, if the "code" matches the code that is provided:

function getCity($string, $array) {
    foreach ($array as $place) {
        if (strstr($string, $place)) { // mine version
            echo "Match found"; 
            return true;
        }
    }
    echo "Not found!";
    return false;
}

This is all I have gotten. I have no idea how to continue.

2
  • Instead of return true, return $place['name'] Commented Jan 12, 2016 at 18:30
  • 2
    where did you get that array, is it json string? Commented Jan 12, 2016 at 18:38

1 Answer 1

1

The "array" that you have is indeed an array, but in JSON, and not a PHP-Array. Therefore, you have to decode it first:

$json = '[
    {
     "kind": "qpxexpress#cityData",
     "code": "YOW",
     "name": "Ottawa"
    },
    {
     "kind": "qpxexpress#cityData",
     "code": "YVR",
     "name": "Vancouver"
    }
]';

$array = json_decode($json, true);

Note here, that the "city": prefix in your code is probably a leftover from the surrounding object inside of that JSON (I also removed some of the entries, as not all of them are required to make my point). So in order to decode only the array it has to be removed.

You can then iterate over the array like you already do:

function getNameByCodeFromArray($array, $code) {
    foreach ($array as $entry) {
        if ($entry['code'] == $code) {
            return $entry['name'];
        }
    }
}

And just call the function:

echo getNameByCodeFromArray($array, 'YVR'); // Echoes "Vancouver"
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.