James Sandzalone James Sandzalone - 23 days ago 5
JSON Question

How to loop through multidimensional array?

I'm currently getting a JSON response from a company's API and converting it into a PHP array like this:

$api_url = file_get_contents('http://example.com');
$api_details = json_decode($api_url, true);


When I run
var_dump
on
$api_details
, I am getting this:

array(2) {
["metadata"]=>
array(5) {
["iserror"]=>
string(5) "false"
["responsetime"]=>
string(5) "0.00s"
["start"]=>
int(1)
["count"]=>
int(99999)
}
["results"]=>
array(3) {
["first"]=>
int(1)
["result"]=>
array(2) {
[0]=>
array(4) {
["total_visitors"]=>
string(4) "3346"
["visitors"]=>
string(4) "3249"
["rpm"]=>
string(4) "0.07"
["revenue"]=>
string(6) "0.2381"
}
[1]=>
array(4) {
["total_visitors"]=>
string(6) "861809"
["visitors"]=>
string(6) "470581"
["rpm"]=>
string(4) "0.02"
["revenue"]=>
string(7) "13.8072"
}
}
}
}


I'm trying to do 2 things and can't figure out how to do either with a multidimensional array.


  1. I need to check to see if
    metadata > iserror
    is
    false
    . If it is not false, I want to show an error message and not continue with the script.

  2. If it is
    false
    , then I wants to loop through the results of
    results > result
    and echo the
    total_visitors
    ,
    visitors
    , etc for each of them.



I know how to echo data from array, I guess I'm just getting confused when there's multiple levels to the array.

Anyone that can point me in the right direction would be much appreciated :)

Answer

You can iterate over arrays using foreach. You can read up on it here: http://php.net/manual/en/control-structures.foreach.php

Since you're using associative arrays, your code will look something like this:

if ($arr['metadata']['iserror']) {
  // Display error here
} else {
  foreach($arr['results']['result'] as $result) {
    echo $result['total_visitors'];
    echo $result['visitors'];
  }
}

You'll have to tweak the code to fit exactly what you're doing, but this should get you over the line.

Hope that helps!