i been trying to extract data from json with the following format:
[{"_type":"pipe","time":"2013-10-25 02:42:51","1_price":["00.00"],"1_name":["name"],"_template":"675fgy","1_purl":["http://"],"_cached_page_id":"te487","1_image":["image.jpeg"],"url":"http://"},
[{"_type":"pipe","time":"2013-10-25 02:42:55","1_price":["00.00"],"1_name":["name"],"_template":"16778f","1_purl":["http://"],"_cached_page_id":"456gt","1_image":["image.jpeg"],"url":"http://"},
my following code returns "Array2013-10-25 02:42:51" ie. it only returns the value of "time" cant seem to get the value "1_name"
please tell me what im doing wrong
$url = "http://.../api.output";
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
$arr = json_decode($result, true);
foreach($arr as $val)
{
echo $val['1_name'];
echo $val['time'];
}
If you print_r
the result of the json_decode
, you'll see something like this:
Array
(
[0] => Array
(
[_type] => pipe
[time] => 2013-10-25 02:42:51
[1_price] => Array
(
[0] => 00.00
)
[1_name] => Array
(
[0] => name
)
[_template] => 675fgy
[1_purl] => Array
(
[0] => http://
)
[_cached_page_id] => te487
[1_image] => Array
(
[0] => image.jpeg
)
[url] => http://
)
[1] => Array
(
[_type] => pipe
[time] => 2013-10-25 02:42:55
[1_price] => Array
(
[0] => 00.00
)
[1_name] => Array
(
[0] => name
)
[_template] => 16778f
[1_purl] => Array
(
[0] => http://
)
[_cached_page_id] => 456gt
[1_image] => Array
(
[0] => image.jpeg
)
[url] => http://
)
)
So, you have an Array in $arr
, which makes that a good variable name.
The first element of $arr
has key 0
(that's what the [0] =>
means) and is also an Array, but an associative one (it has strings as keys instead of numbers). The first key is _type
, the second is time
, and so on.
If you look at the value of the 1_name
key, you'll see that it is yet another level of Array. It has a single entry, with a numeric key. If you want that value, then you'll have to index to get to it. The full path is $arr[0]['1_name'][0]
.
But you don't want just $arr[0]
, you want all the elements of $arr
, so you're looping over them. That's fine, that just means the $val
takes the place of $arr[whatever]
, so you have $val['1_name'][0]
. The same goes for 1_price
, 1_purl
, etc. But not for _type
or time
or the other keys that don't show arrays.
Modify your for
loop like this
$i=0;
foreach($arr as $k=>$v)
{
echo $arr['1_name'][$i];
echo $arr['time'];
$i++;
}