2016-08-11 103 views
0

它的返回是這樣的:數組返回重複JSON數據

[ 
     { 
     "0": "1", 
     "1": "Udon House", 
     "2": "food", 
     "3": "31.5076701", 
     "4": "74.3544522", 
     "5": "a trip to the landa.", 
     "6": "images/udonHouse.jpg", 
     "place_id": "1", 
     "place_name": "Udon House", 
     "category": "food", 
     "lat": "31.5076701", 
     "lon": "74.3544522", 
     "description": "a trip to the landa.", 
     "db_image": "images/udonHouse.jpg" 
     }, 
     { 
     "0": "5", 
     "1": "Lahore Meuseum", 
     "2": "attractions", 
     "3": "31.5681556", 
     "4": "74.3061492", 
     "5": "want to discover histroy?", 
     "6": "images/badshahi.jpg", 
     "place_id": "5", 
     "place_name": "Lahore Meuseum", 
     "category": "attractions", 
     "lat": "31.5681556", 
     "lon": "74.3061492", 
     "description": "want to discover histroy?", 
     "db_image": "images/badshahi.jpg" 
     } 
    ] 

這是我的PHP代碼:

<?php 
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="tourist"; // Database name 
    $con = mysqli_connect("$host", "$username", "$password","$db_name")or die("cannot connect"); 

if($con){ 

    mysqli_set_charset($con ,'utf8'); 

    $user_id = $_POST['user_id']; 

    $qry = 

    ("SELECT p.* 
FROM 
    places p INNER JOIN 
    favorites f ON p.place_id = f.place_id INNER JOIN 
    user u ON u.id = f.user_id 
WHERE 
    u.id = $user_id"); 

    $query=mysqli_query($con ,$qry);   

    if (!$query) { 
       $message = 'Invalid query: ' . mysqli_error() . "\n"; 
       $message .= 'Whole query: ' . $qry; 
       die($message); 
    } 

    $return_arr = array(); 


    $num_rows = mysqli_num_rows($query); 
    if ($num_rows > 0) { 
     while ($r = mysqli_fetch_array($query)) { 


      header('Content-Type: application/json'); 

      array_push($return_arr,$r); 
     } 
     echo json_encode($return_arr); 
    } 
    } 

?> 

爲什麼返回行兩次在一個對象,我只希望與名稱不符的數據我在這裏做錯了什麼? 請提供任何建議或替代解決方案?

+5

默認情況下'mysqli_fetch_array'返回數字和關聯數組的結果,你可以使用第二個參數來設置你想要的那一個,它將是'mysqli_fetch_array($ query,MYSQLI_ASSOC);' – cmorrissey

+2

,因爲你正在抓取數組,我不使用mysqli但我認爲有這樣的mysqli_fetch_array($查詢,MYSQLI_ASSOC)這將保持您的數組的鍵而不是你不需要的索引 –

+1

@cmorrissey^_^ –

回答

0

通過默認mysqli_fetch_array功能,使用MYSQLI_BOTH作爲其「結果類型」。

您需要將第二個參數設置爲MYSQLI_ASSOC以使其僅返回鍵名稱。

while ($r = mysqli_fetch_array($query, MYSQLI_ASSOC)){ 
    array_push($return_arr,$r); 
} 

P.S. header('Content-Type: application/json');只需要調用一次,因此請將其從while循環中取出。