0

I've this array:

Array
(
    [Europa] => Array
        (
            [0] => Array
                (
                    [AVA_Id] => 1
                    [AVA_Country] => France
                    [AVA_City] => Paris
                )
        )
    [America] => Array
        (
            [0] => Array
                (
                    [AVA_Id] => 2
                    [AVA_Country] => Canada
                    [AVA_City] => Ottawa
                )
        )
)

I would like to read the 'Europa' section and get the City if the country is France.

Do you know why this code isn't working ?

foreach($bigArray as $key => $array) {
    $value = $array[2];
    if($bigArray[AVA_Country] == 'France')) {
        echo $bigArray['AVA_City']
    }
    else {
        echo 'No city found';        
    }
}

Thanks.

2 Answers 2

1

You should be checking $array in your loop, not $bigArray. Note you are also missing 's around AVA_Country, and there is an extra ) in your if statement and a missing ; from echo $value['AVA_City']. Additionally, you need to use another level of nesting to access the AVA* values, and there is no $array[2] value in your sample data so I've removed that line of code.

$found = false;
foreach($bigArray as $key => $array) {
    foreach ($array as $value) {
        if($value['AVA_Country'] == 'France') {
            echo $value['AVA_City'];
            $found = true;
        }
    }
    if (!$found) echo "No city found";
}

Output:

Paris

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

4 Comments

And $array doesn't have "2" as a key, and you never use the $value that you attempt to extract with that anyway...
This assumes you are iterating over the Europe subarray (in other words, $bigArray is actually Europe and not the whole array in the question)
@GregSchmidt thanks for the input, I've updated the answer.
@KodosJohnson thanks for the input, I've updated the answer.
0

You doesn't loop over all the deep of arrays.

$country = 'France';
$city = '';
$found = false;

foreach($world as $key => $continent) {
  foreach($continent as $k => $region) {
    if($region['AVA_Country'] == $country)) {
      $city = $region['AVA_City'];
      $found = true;
      break;
    }
  }
  if($found) break;
}
echo $city;

Comments

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.