Home > Mobile >  Fatal error when using foreach on 3rd array
Fatal error when using foreach on 3rd array

Time:12-07

I'm getting an error when trying to use foreach on 3rd array

'{
  "prefix": "_country-",
  "countries": [
    {
      "code": "al",
      "name": "Albania",
      "cities": {
        "prefix": "_city-",
        "options": [
          {
            "code": "durres"
              },
          {
            "code": "tirana"
          }
        ]
      }
},
    {
      "code": "dz",
      "name": "Algeria",
      "cities": {
        "prefix": "_city-",
        "options": [
          {
            "code": "algiers"
          },
          {
            "code": "oran"
          }
        ]
      }
    }
  ]
}

My goal is to get those data above and expect it to loop until its last data using this code:

`foreach($countryarr1['countries'] as $countkey1 => $countname1){ ?> <br><br> <?php 
  foreach($countname1['cities'] as $cntrykey2 => $cntrys){
    foreach($cntrys['options'] as $optionskey1 => $optionsarr1){
      var_dump($optionsarr1);
    }
  }
}`

It returns this error

'Fatal error: Uncaught TypeError: Cannot access offset of type string on string in 
C:\xampp\htdocs\homepage\countries.php:25 Stack trace: #0 {main} thrown in 
C:\xampp\htdocs\homepage\countries.php on line 25'

Here is the line 25

Error on line 25

Am I missing something? By the way I'm working on a proxy dashboard for a website.

Here's proof that when I only had 2 arrays it had no problems:

foreach for 2 arrays

output with no errors

Now when I add another foreach on the 3rd array and so forth, there's the error. Here it is.

foreach for 3rd array

And the error error

CodePudding user response:

You can do that quite nicely with only 2 loops like this

$countryarr1 = json_decode($str, true);
#print_r($countryarr1);
foreach($countryarr1['countries'] as $countkey1 => $countname1){ ?> <br><br> <?php 
    foreach($countname1['cities']['options'] as $optionskey1 => $optionsarr1){
        var_dump($optionsarr1);
    }
}

RESULT

array(1) { 'code' => string(6) "durres" }
array(1) { 'code' => string(6) "tirana" }
array(1) { 'code' => string(7) "algiers" }
array(1) {'code' => string(4) "oran" }
  • Related