繁体   English   中英

在php中读取此数组

[英]Read this array in php

我的PHP从Android应用程序收到了此字符串

[{"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"}]

然后在执行$data = json_decode($data,TRUE);

到上面的字符串,它变成:

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
        )

)

但是我不知道该怎么读。 这是我所做的:

//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"];
}

但是它只输出AA A ...

*以上所有数据已显示在<pre></pre>

将json保存到变量,例如$json ,然后运行json_decode($json, true)并将其保存到变量,例如$array 现在,您已经解码了数组中的json。 之后,您可以使用foreach循环遍历数组。 要摆脱某些%2C%...字符,请在子数组的每个元素上运行urldecode 这是一个例子:

<?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/>';
}

结果是:

2
Food, Drinks & Clothes
Nasi Lemak, Teh Tarik 
5

3
Food, Drinks & Clothes
Rori Canai
3
array_walk_recursive(json_decode($json, true), function(&$item, $key){
    $item = urldecode($item);
});

foreach ($array as $item) {
    ..
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM