douping4436 2018-05-29 09:54
浏览 56
已采纳

循环通过json数据

I have a a script that generate JSON-data with this struture. Im trying to loop out this is a HTML list with PHP but now getting it right.

This is the structure of the JSON:

{
  "msg": [
    "msg text 1",
    "msg text 2",
    "msg text 3",
    "msg text 4",
    "msg text 5",
    "msg text 6"
  ]
}

My PHP code looks like this:

$json = file_get_contents('my_json_file');
$results = json_decode($json);
$array = (array)$results;

foreach ($array as $key => $item){
        echo "Key: ".$key." Item: ".$item;
}

Output of this code is:

Key: msg Item: Array

Anyone who knows what i have to edit in order to get this right?

  • 写回答

2条回答 默认 最新

  • doudeng9425 2018-05-29 10:01
    关注

    You have to do the foreach on array['msg'] to get all the msg items. otherwise you will loop over all the properties of the main array (in this case there is only msg)

    $json = file_get_contents('my_json_file');
    $results = json_decode($json);
    $array = (array)$results;
    
    foreach ($array['msg'] as $item){
            echo "Key: msg Item: ".$item;
    }
    

    The output will be :

    Key: msg Item: msg text 1 
    Key: msg Item: msg text 2
    ...
    

    If you still want to loop over the main array and want to print the content of msg, you have to use print_r to print the content of the array

    $json = file_get_contents('my_json_file');
    $results = json_decode($json);
    $array = (array)$results;
    
    foreach ($array as $key => $item){
        echo "Key: ".$key." Item: ".print_r($item, true);
    }
    

    The output will be :

    Key: msg Item: array [
        "msg text 1",
        "msg text 2",
        ...
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路