2016-10-09 4 views
0

私のPHPは、上記の文字列に$data = json_decode($data,TRUE);PHPでこの配列を読む

をやった後

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

次にAndroidアプリからこの文字列を受け取った、それは次のようになります。

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を出力...

*例 $json、および実行のための上記すでに変数に <pre></pre>

+0

あなたがデコード前に '$のdata'の実際の値は何ですかこれは一例ですか?もしあなたが 'var_dump($ data)'をデコードしたらどうなるでしょうか?また、私は別の変数名に割り当てることをお勧めします。 –

+0

あなたはどこか 'urlencode()'を使いましたか?もしそうなら、それの代わりに 'rawurlencode()'を使います。 –

+2

これはうまく動作しますhttps://3v4l.org/2Znq2 –

答えて

1

保存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 
0
array_walk_recursive(json_decode($json, true), function(&$item, $key){ 
    $item = urldecode($item); 
}); 

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