doulv1760 2017-02-23 08:34
浏览 37
已采纳

条件为json数组通过PHP

I'm Parsing This json Array and I Want to Take text Object of answer and Put That in New Column awnser2, and This is one Row of My json Rows, answer 38 and 39 in json Are Same as text But anser 40 Is Descriptive Awnser, I Got Illegal string offset 'text' for Hello Word, How Can I Make a Condition to Have Both of Them in Output?

[{"id":"38","answer":[{"option":"3","text":"HIGH"}],"type":"a"},
 {"id":"39","answer":[{"option":"3","text":"LOW"}],"type":"b"},
 {"id":"40","answer":["Hello Word"],"type":"c"}]

This Is My Code:

<?php
$con=mysqli_connect("localhost","root","","array");
mysqli_set_charset($con,"utf8");

// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT survey_answers,us_id FROM user_survey_start";
if ($result=mysqli_query($con,$sql)){
while ($row = mysqli_fetch_row($result)){
$json = $row[0];
if(!is_null($json)){

$json = preg_replace('/|

/','
',trim($json));

$jason_array = json_decode($json,true);
$answers = array();
foreach ($jason_array as $data) {
if (array_key_exists('answer', $data)) {

foreach($data['answer'] as $ans){
$answers[] =$ans['text'] ;
}
}
}
if(!empty($answers)) {
$answers= implode('

  • 写回答

1条回答 默认 最新

  • dongshang1979 2017-02-23 08:45
    关注

    check key is set or not otherwise assign value

    foreach ($jason_array as $data) {
                        if (array_key_exists('answer', $data)) {   
                            foreach($data['answer'] as $ans){
                                  $answers[] = isset($ans['text']) ? $ans['text'] : $ans;                                
                            }
                        }
                }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?