gpt4 book ai didi

php - 通过 PHP 解决 JSON 中的换行

转载 作者:行者123 更新时间:2023-11-29 04:05:42 30 4
gpt4 key购买 nike

我正在解析这个 json 数组,我想获取 type 对象并将其放入新列 type2,这是一行 我的 json 行,由于某些行中的 json 换行,我得到为 foreach() 提供的无效参数。我该如何解决这个问题?

这个不行

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

这一个没问题

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

这是我的代码:

<?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);
?>

最佳答案

在 json 解码之前用\n 替换你的新行:

$json = preg_replace('/\r|\n/','\n',trim($json));

$jason_array = json_decode($json,true);

关于php - 通过 PHP 解决 JSON 中的换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42408472/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com