使用PHP收集JSON数组中的前三个条目

I've got this JSON array that contains data from a Google Analytics account. I want to collect the first three entries of this array and display using PHP. The problem is, I don't know the key to collect. Because it may vary. JSON looks like this:

"browsers": {
    "Android Browser": 721,
    "Chrome": 3362,
    "Firefox": 912,
    "Internet Explorer": 1776,
    "Mozilla": 3,
    "Opera": 190,
    "Safari": 4501,
    "Safari (in-app)": 284,
    "Mozilla Compatible Agent": 82,
    "Opera Mini": 7,
    "Amazon Silk": 3,
    "IE with Chrome Frame": 2,
    "SeaMonkey": 1,
    "KlappAppiPhone2": 8,
    "Maxthon": 3
}

So I need to iterate through this array and print out both key and value. I'm not that strong at PHP yet, and I thought I could just run a loop and echo out each value, something like this:

<?php
    foreach($json->mobile as $row)
    {
        foreach($row as $key => $val)
        {
            echo $key . ': ' . $val;
            echo '<br>';
        }
    }
?>

But I get an error Invalid argument supplied for foreach(). After googling that error, I found this snippet: if (is_array($values)) and I include that, nothing is echoed out. Is this not an array? What am I doing wrong?

Follow this ...

  • Make use of json_decode()
  • You don't need of two foreach in this context
  • Set a flag so you could just display the first three values

The code

<?php
    $json = json_decode($yourjsonstring);
    $i=0;
    foreach($json->mobile as $key => $val)
    {
        if($i<=2)
        {
            echo $key . ': ' . $val;
            echo '<br>';
            $i++;
        }

    }
<?php
    $jsondata="your json data here";
    $mobile=json_decode($jsondata);
    foreach($mobile as $row)
    {
        foreach($row as $key => $val)
        {
            echo $key . ': ' . $val;
            echo '<br>';
        }
    }
?>

Before send JSON string to foreach decode that with json_decode() function.

For example:

$json = {
   "mobile": {
        "iPad": 30,
        "Lumia 920": 2,
        "iPhone": 105,
        "Nexus 4": 4,
        "GT-I9100": 5,
        "GT-I9300": 6,
        "GT-N8000": 1,
        "GT-P5100": 2
    }
}
$decode = json_decode($json);
foreach($decode->mobile as $key => $value) {
    echo $key . ': ' . $val;
    echo '<br>';
}