我的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"];
}
但它只输出A A A ......
*以上所有数据都已显示在<pre></pre>
答案 0 :(得分:1)
将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
答案 1 :(得分:0)
array_walk_recursive(json_decode($json, true), function(&$item, $key){
$item = urldecode($item);
});
foreach ($array as $item) {
..
}