Anthony Anthony - 8 months ago 29
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


echo $answer->option;
// will output


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?


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:

// 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!


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

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