imin
imin

Reputation: 4578

Read this array in 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>

Upvotes: 0

Views: 54

Answers (2)

Hany Alsamman
Hany Alsamman

Reputation: 501

array_walk_recursive(json_decode($json, true), function(&$item, $key){
    $item = urldecode($item);
});

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

Upvotes: 0

aslawin
aslawin

Reputation: 1981

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

Upvotes: 1

Related Questions