从json数据中删除空格

Mud*_*yed 0 php arrays json

我有从数据库中获取数据的脚本.这些数据是多维数组.你可以说数组数组和输出以json格式编码.我的问题是如何从每个json值的开头和结尾删除空格.

输出是: -

 {"post":{"id":"4","image":" LIVE_3.JPG ","video":"LIVE_3.MOV","category":""}},
 {"post":{"id":"3","image":" LIVE_2.JPG ","video":"LIVE_2.MOV","category":""}},
 {"post":{"id":"2","image":"LIVE_1.JPG","video":"LIVE_1.MOV","category":""}}  
Run Code Online (Sandbox Code Playgroud)

需要和预期: -

{"post":{"id":"4","image":"LIVE_3.JPG ","video":"LIVE_3.MOV","category":""}},
{"post":{"id":"3","image":"LIVE_2.JPG ","video":"LIVE_2.MOV","category":""}},
{"post":{"id":"2","image":"LIVE_1.JPG","video":"LIVE_1.MOV","category":""}}
Run Code Online (Sandbox Code Playgroud)

我的代码是: -

$query = "SELECT * FROM data  ORDER BY ID DESC ";
$result = mysql_query($query,$link) or die('Errant query:  '.$query);

/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
        $posts[] = array('post'=>$post);


    }
}

/* output in necessary format */

    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));




/* disconnect from the db */
@mysql_close($link);
Run Code Online (Sandbox Code Playgroud)

has*_*san 5

用于trim删除空格,但最好在将数据插入数据库之前验证和清理数据

if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
        $post['image'] = trim($post['image']);
        $posts[] = array('post'=>$post);
    }
}
Run Code Online (Sandbox Code Playgroud)

PS.请mysql_*立即停止使用扩展,它已经死了,已经从PHP7.x中移除了,所以你的代码应该是这样的: -

$query = "SELECT * FROM data  ORDER BY ID DESC ";
$result = mysqli_query($link, $query) or die('Errant query:  '.$query);

/* create one master array of the records */
$posts = array();
if(mysqli_num_rows($result)) {
    while($post = mysqli_fetch_assoc($result)) {
        $post['image'] = trim($post['image']);
        $posts[] = array('post'=>$post);
    }
}
Run Code Online (Sandbox Code Playgroud)

不要忘记编辑从mysql_*到mysqli_*的连接

  • 注意@ ADyson对这个问题的评论;**不要使用`mysql_`**.这回答了使用现有代码的问题,但应该使用[`mysqli_`](http://php.net/manual/en/book.mysqli.php)重新编写. (2认同)