从json数据中删除空格

时间:2018-09-19 12:50:38

标签: php arrays json

我有从数据库中获取数据的脚本。这些数据是多维数组。您可以说是array数组,而输出则以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":""}}  

需要和期望:-

{"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":""}}

我的代码是:-

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

1 个答案:

答案 0 :(得分:5)

使用trim删除空格,但是最好在将数据插入数据库之前对其进行验证和清理

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

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

别忘了编辑从mysql_ *到mysqli_ *的连接