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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀