dragon8997474 2014-02-03 12:10
浏览 50
已采纳

使用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?

  • 写回答

3条回答 默认 最新

  • dongque8332 2014-02-03 12:17
    关注

    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++;
            }
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?