strange json foreach get specified value

风格不统一 提交于 2020-01-07 02:53:09

问题


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!


回答1:


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
} 



回答2:


try

$ansopts = json_decode( $answer->option,true );
foreach($ansopts as $mydata)
{
     foreach($mydata->customer_ans as $values)
     {
          echo $values . "\n";
     }
}

or you can try to dump the variable first

print_r($ansopts);exit;


来源:https://stackoverflow.com/questions/39041324/strange-json-foreach-get-specified-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!