格式化JSON输出

时间:2015-02-09 07:25:30

标签: php jquery json

我正在尝试使用 http://loopj.com/jquery-tokeninput

我的PHP代码如下

$data = array();
$result=$this->ArticleTag->query("SELECT * FROM tbl_article_tags where name LIKE '".$_GET['q']."%'");
foreach ($result as $row){
$name ='id:'.$row['tbl_article_tags'] ['id'].',name:'.$row['tbl_article_tags']['name'];
array_push($data, $name);   
}   
echo json_encode($data);

给出了输出

["id :57, name :Editorial The Corporate","id :15, name :editorial","id :93, name :Editorial from abroad"]

我需要以下列格式输出JSON搜索结果:

[
    {"id":"856","name":"House"},
    {"id":"1035","name":"Desperate Housewives"},
    ...
]

我尝试了不同的组合,但没有奏效。请帮忙。

4 个答案:

答案 0 :(得分:1)

Try this:完整代码解决方案>你的问题出在$name变量..

    $data = array();
    $result=$this->ArticleTag->query("SELECT * FROM tbl_article_tags where name LIKE '".$_GET['q']."%'");
    foreach ($result as $row){
    $name = array(
          'id' => $row['tbl_article_tags']['id'],
          'name' => $row['tbl_article_tags']['name']
           );
        $data[]=$name;   
    }   
    echo json_encode($data);

答案 1 :(得分:0)

试试此代码

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

http://php.net/manual/en/function.json-encode.php

答案 2 :(得分:0)

$name = array('id' => $row['tbl_article_tags']['id'], 'name' => $row['tbl_article_tags']['name']);

json_encode适用于多维数组

答案 3 :(得分:-1)

您可以使用2个数组,因此值将配对。

$data = array();
foreach ($result as $row) {
    $tempArray = array(
            ['id'] = $row['tbl_article_tags'],
            ['name'] = $row['tbl_article_tags']['name']);
    array_push($data, $tempArray);   
}   
echo json_encode($data);