dsh77114 2017-02-23 06:23
浏览 43
已采纳

通过PHP解决JSON中的新行

I'm Parsing This json Array and I Want to Take type Object and Put That in New Column type2, and This is one Row of My json Rows, I Get Invalid argument supplied for foreach() Because of New Line in json in Some Rows. How Can I Solve This?

This One is Not Okey

[{"id":"26","answer":[{"option":"4","text":"Hello
"}],"type":"3"}]

AndThis One is Okey

[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}]

And 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)){
            $jason_array = json_decode($json,true);
            // type2
            $type = array();
            foreach ($jason_array as $data) {
                if (array_key_exists('type', $data)) {
                    // Now we will only use it if it actually exists
                    $type[] = $data['type'];
                }
            }         
            // lets check first your $types variable has value or not?
            if(!empty($type)) {
             $types= implode(',',$type); /// implode yes if you got values
            } 
            else { 
                $types = ''; //blank if not have any values
            }
            $sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql
            echo $sql2."<br>";
            mysqli_query($con,$sql2);
        }
    }
}
mysqli_close($con);
?>
  • 写回答

2条回答 默认 最新

  • doubinchou4219 2017-02-23 06:38
    关注

    Replace your new line with before json decode:

    $json = preg_replace('/|
    /','
    ',trim($json));
    
    $jason_array = json_decode($json,true);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势