James Sandzalone James Sandzalone - 10 months ago 35
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
, I am getting this:

array(2) {
array(5) {
string(5) "false"
string(5) "0.00s"
array(3) {
array(2) {
array(4) {
string(4) "3346"
string(4) "3249"
string(4) "0.07"
string(6) "0.2381"
array(4) {
string(6) "861809"
string(6) "470581"
string(4) "0.02"
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
    . If it is not false, I want to show an error message and not continue with the script.

  2. If it is
    , then I wants to loop through the results of
    results > result
    and echo the
    , 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 Source

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!