2015-12-16 59 views
1

我必須將兩個數組合併成單個內部Json編碼。我的代碼,將兩個數組合併成單個內部json_encode

$email = $_GET["email"]; 
    $password = $_GET["password"]; 

    $query  = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'"; 
    $result  = mysqli_query($c, $query) or die(mysqli_error($c)); 
    $length  = mysqli_num_rows($result); 

    if($length == 1) 
    { 
     $var[] = array('status'=>"success"); 

     while($obj = mysqli_fetch_object($result)) 
     { 
      $var[] = $obj; 
     } 
     echo '{"login":'.json_encode($var).'}'; 
    } 
    else 
    { 
     $arr = array('status'=>"notfound"); 
     echo '{"login":['.json_encode($arr).']}'; 
    } 

現在的結果是,

{"login":[{"status":"success"},{"login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"[email protected]","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]} 

而且需要輸出,

{"login":[{"status":"success","login_id":"1","name":"Jithin Varghese","password":"some","phone":"","email":"[email protected]","addr":"","city":"","state":"","pincode":"0","type":"STD","verification":"1"}]} 

如何組合排列。我嘗試了很多。

+0

您不能在沒有驗證的情況下在您的SQL查詢中使用用戶輸入,那麼您可以操作SQL注入攻擊。請看[準備好的語句](http://php.net/manual/de/mysqli.quickstart.prepared-statements.php) – KhorneHoly

回答

4

變化

$var[] = array('status'=>"success"); 
while($obj = mysqli_fetch_object($result)) 
{ 
    $var[] = $obj; 
} 

$var['status'] = "success"; 
// use the assoc fetch here.. to avoid casting to array 
while($arr = mysqli_fetch_assoc($result)) 
{ 
    $var = array_merge($var, $arr); 
} 
+0

現在結果是'{「login」:{「status」:「success 「,」0「:{」login_id「:」1「,」name「:」Jithin Varghese「,」password「:」some「,」phone「:」「,」email「:」[email protected]「 ,「addr」:「」,「city」:「」,「state」:「」,「pincode」:「0」,「type」:「STD」,「verification」:「1」}}}' –

+1

好。謝謝。現在它正在工作。 –

0

這是一個瘋狂的猜測,但嘗試。

​​
1

您可以使用array_merge得到你要求精確的輸出:

$email = $_GET["email"]; 
$password = $_GET["password"]; 

$query  = "SELECT * FROM tbl_user_login WHERE email='$email' AND password='$password' AND verification='1'"; 
$result  = mysqli_query($c, $query) or die(mysqli_error($c)); 
$length  = mysqli_num_rows($result); 

$response = []; 
if($length == 1) 
{ 
    $response['login'] = arry(array_merge(array('status'=>"success"), mysqli_fetch_assoc($result))); 
} 
else 
{ 
    $response['login'] = array(array('status'=>"notfound")); 
} 

header('Content-Type: application/json'); 
echo json_encode($response); 

注意,似乎沒有必要有login屬性是一個數組時,只有一個結果,所以它纔有意義刪除外部陣列包裝:

if($length == 1) 
{ 
    $response['login'] = array_merge(array('status'=>"success"), mysqli_fetch_assoc($result)); 
} 
else 
{ 
    $response['login'] = array('status'=>"notfound"); 
}