Anthony Anthony - 3 months ago 10
JSON Question

strange json foreach get specified value

i have a json code,tried a lot of ways but still can't get the data from the json

json:

echo $answer->option;
// will output

{"customer_ans":["qqq","sss"],
"show_image":["images/a.png","images/b.png"]},
{"customer_ans":["ooo","ooo","ooo"],
"show_image":["images/a.png","images/b.png","images/c.png"]}
...thesame...blablabla


when i tried

foreach($answer->option as $mydata)

{

foreach($mydata->customer_ans as $values)
{
echo $values . "\n";
}
}


no output and I tried

$ansopts = json_decode( $answer->option,true );
for($i=0;$i<count($ansopts["customer_ans"]);$i++) {
echo $ansopts["customer_ans"][$i];
}


still no output!

So how can I get the customer_ans value?

**********************************************Update*****************

for($i=0;$i<count($ansopts);$i++) {
echo var_export( $ansopts["customer_ans"][$i]);
}


no ouput

echo '<pre>'.print_r(json_decode($answer->option, true), true).'</pre>';


no output

var_dump function:

var_dump($answer->option);
// will output
string(291) "{"customer_ans":["aaa","bbb"],"show_image":["images/a.png","images/a.png"]},{"customer_ans":["ccc","ddd","eee"],"show_image":["images/a.png","images/b.png","images/c.png"]}"


Many thanks everyone!

Answer

Try it this way:

#the json is a littel invalid to parse, missing [ ] around it 
$ansopts = json_decode('['.trim((string)$answer->option).']',true );

//test for errors
print json_last_error_msg ();
//to see it for real
var_export($ansopts);

//loop 
for($i=0;$i<count($ansopts);$i++) {
    echo $ansopts[$i]["customer_ans"][0];#qqq
    echo $ansopts[$i]["customer_ans"][1];#sss
}