3

My json is

{"productInfoList":[{"prod":"Some Products","price":"someprice"},{"prod":"Another Product","price":"48"}]}

My php code is

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$voo = curl_exec($ch);
curl_close($ch);
$yf= json_decode($voo,true); 
for ($i=0; $i < 5; $i++)
{
$fkname = $yf->{'productInfoList'}[$i]->{'prod'};
echo $i;
echo $fkname;
}
?>

Output is 012345. How can I get product names using json? The json file is totally fine I checked it using http://jsonviewer.stack.hu/.

asked Aug 27, 2015 at 6:02

3 Answers 3

2

After json_decode, the json is converted to a php array.Try replacing this line:

$fkname = $yf->{'productInfoList'}[$i]->{'prod'};

With this line:

$fkname = $yf['productInfoList'][$i]['prod']; 

Here is a working DEMO

Code Improvement
In your loop, use the array size instead of hard-coding the length:

for ($i=0; $i < sizeOf($yf['productInfoList']); $i++)
{
$fkname = $yf['productInfoList'][$i]['prod'];
 echo $fkname."<BR />";
}
answered Aug 27, 2015 at 6:05

5 Comments

Great but if I remove true then?
Ok you were faster than gonzalon so you win the checkmark, upvoted both.
@IdidntKnewIt please check the demo for your code improvement
@IdidntKnewIt sorry i had a typo in my demo, please check it again
@IdidntKnewIt the browser is removing my i++ in the demo i provide, please edit it before you run it
2

Like this would work:

$yf= json_decode($voo,true); 
$arr = $yf['productInfoList'];
for ($i=0; $i < sizeof($arr); $i++)
{
$fkname = $arr[$i]['prod'];
echo $i;
echo $fkname;
}

Take in count the sizeof function for iterating over an array.

The output would be:

0Some Products1Another Product

answered Aug 27, 2015 at 6:09

Comments

1

use foreach and its simple

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://example.com/file.json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$voo = curl_exec($ch);
curl_close($ch);
$yf= json_decode($voo,true); 
$i = 0;
foreach($yf['productInfoList'] as $product)
{ 
 echo $i.' - '.$product['prod'].'<br />';
 $i++;
}
?>
answered Aug 27, 2015 at 6:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.