2015-02-09 246 views
-1

我想使用 http://loopj.com/jquery-tokeninput格式化JSON輸出

我的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"}, 
    ... 
] 

我試過不同的組合,但沒有工作。請幫忙。

回答

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); 
0
$name = array('id' => $row['tbl_article_tags']['id'], 'name' => $row['tbl_article_tags']['name']); 

json_encode作品與多維數組

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