-2

I have the following JSON code:

{
   "google.com": {
        "clicks": 23,
        "browsers": {
            "Chrome": 19,
            "Mozilla": 2,
            "Safari": 1
        }
    },
    "mcnitro.net": {
        "clicks": 87,
        "browsers": {
            "Chrome": 19,
            "Mozilla": 2,
            "Safari": 1
        }
    }
}

And I am endeavouring to print on the document page the arrays' names and their children. So far, I have tried the following PHP code:

<?php
    header("Content-type: text/javascript");
    $jsonString = file_get_contents('stats.json');
    $data = json_decode($jsonString, true);
    foreach($data->children() as $domain) {
        echo $data[$domain];
        foreach($data[$domain] as $value) {
            echo $value['clicks'];
        }
    }
?>

However, I am facing an issue in the error_log:

PHP Fatal error:  Call to a member function children() on array in /home/gamin167/public_html/ads/engine/300x250/gen.js.php on line 5

The result wanted was to have "google.com" and "mcnitro.net" printed, as well as their "clicks" property.

Any tip or advice will be highly appreciated! Thanks in advance!

undefined
  • 1,019
  • 12
  • 24
  • What makes you think $data was an object that had a `children` method …? – CBroe May 25 '18 at 07:08
  • 1
    `$data` will be an associative array, that which doesn't have a function named `children()`. `foreach($data->children() as $domain) {` should be replaced with `foreach($data as $k=>$doman){`.. – Romeo Sierra May 25 '18 at 07:09
  • No idea, to be impartial. I am rather fresh to PHP and have discovered that composition of code on the Internet. – undefined May 25 '18 at 07:11
  • 1
    `children()` looks more like an XML method, which is just another data file format. – Nigel Ren May 25 '18 at 07:13

2 Answers2

0

You decode the string to an array with true yet you seem to try and use it as an object.
Also there is no need to loop twice.

foreach($data as $key => $domain) {
    echo $key . "\n";
    echo $domain['clicks'] . "\n\n";

}

output:

google.com
23

mcnitro.net
87

https://3v4l.org/D7FCY

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

You cannot use ->children(). $data is an array with your json data, and you can use foreach to get key and value, like foreach ($data as $key => $value).

So here, to get your domain name, just do :

<?php
    header("Content-type: text/javascript");
    $jsonString = file_get_contents('stats.json');
    $data = json_decode($jsonString, true);
    foreach($data as $domain => $value) {
        echo $value['clicks'];
    }
?>
Jouby
  • 2,196
  • 2
  • 21
  • 33