douzhi7451 2016-10-09 17:09
浏览 55
已采纳

在php中读取此数组

My PHP received this string from an Android app

[{"id":2,"category":"Food%2C%20Drinks%20%26%20Clothes","description":"Nasi%20Lemak%2C%20Teh%20Tarik%20","cost":"5","transactionDate":"2016-10-04"},{"id":3,"category":"Food%2C%20Drinks%20%26%20Clothes","description":"Rori%20Canai","cost":"3"}]

Then after doing $data = json_decode($data,TRUE);

to the string above, it become:

Array
(
    [0] => Array
        (
            [id] => 2
            [category] => Food%2C%20Drinks%20%26%20Clothes
            [description] => Nasi%20Lemak%2C%20Teh%20Tarik%20
            [cost] => 5
        )

    [1] => Array
        (
            [id] => 3
            [category] => Food%2C%20Drinks%20%26%20Clothes
            [description] => Roti%20Canai
            [cost] => 3
        )

)

But I don't know how to read it. Here's what I did:

//I pass the data above into variable $data

$data = json_decode($data,TRUE);

for ($i = 0; $i < count($data); $i++){    
 echo "id: ".$data[$i]["id"]. ", desc: ".$data[$i]["description"]. ", cost: ".$data[$i]["cost"];
}

but it just outputs A A A...

*All the data above is already displayed in <pre></pre>

  • 写回答

2条回答 默认 最新

  • duanquan1876 2016-10-09 17:39
    关注

    Save json to variable, for example $json, and run json_decode($json, true) and save it to variable, for example $array. Now you have decoded json in array. After that you can iterate through array using foreach loop. To get rid of some %2C%... characters, run urldecodeon every element of subarray. This is an example:

    <?php
    
    $json = '[{"id":2,"category":"Food%2C%20Drinks%20%26%20Clothes","description":"Nasi%20Lemak%2C%20Teh%20Tarik%20","cost":"5","transactionDate":"2016-10-04"},{"id":3,"category":"Food%2C%20Drinks%20%26%20Clothes","description":"Rori%20Canai","cost":"3"}]
    ';
    
    $array = json_decode($json, true);
    
    foreach($array as $subArray)
    {
        echo urldecode($subArray['id']).'<br/>';
        echo urldecode($subArray['category']).'<br/>';
        echo urldecode($subArray['description']).'<br/>';
        echo urldecode($subArray['cost']).'<br/><br/>';
    }
    

    And result is:

    2
    Food, Drinks & Clothes
    Nasi Lemak, Teh Tarik 
    5
    
    3
    Food, Drinks & Clothes
    Rori Canai
    3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?