2017-04-19 107 views
1

我有一個關於API JSON輸出的問題。當我在一個循環中陷入JSON輸出時,當我迫使數組格式更改爲索引數組時,它正在創建自己的索引。如何更改PHP中的對象中的JSON數組的輸出?

PHP代碼:

$sql = "SELECT name,fname,address FROM user_management"; 
$array = array(); 

$result = $conn->query($sql); 
$i=1; 

if ($result->num_rows > 0) { 
    // output data of each row 
    $array=["message"=>"success"]; 
    while($row = $result->fetch_assoc()) { 

    $array[] = ["Hello" => $row]; 

} 

} 
else 
{ 
    echo "0 results"; 
} 
//echo implode(',', $array); 
// Take output array glue it with the 
echo json_encode($array); 
$conn->close(); 
?> 

我得到的迴應:

{ 
    "message": "success", 
    "0": { 
    "Hello": { 
     "name": "harjot", 
     "fname": "tejinder", 
     "address": "noida" 
    } 
    }, 
    "1": { 
    "Hello": { 
     "name": "regret", 
     "fname": "egegrregeger", 
     "address": "gegreg" 
    } 
    }, 
    "2": { 
    "Hello": { 
     "name": "harjot1", 
     "fname": "harjot2", 
     "address": "noida" 
    } 
    }, 
    "3": { 
    "Hello": { 
     "name": "har", 
     "fname": "har1", 
     "address": "Punjab" 
    } 
    } 
} 

我想要的響應,沒有0,1,2,3該數組在其自身的決策。有沒有辦法訪問數組的索引?

預期輸出:

{ "message": "success", 
    "Hello": { 
     "name": "harjot", 
     "fname": "tejinder", 
     "address": "noida" }, 
    "Hello1": { 
     "name": "regret", 
     "fname": "egegrregeger", 
     "address": "gegreg" }, 
    "Hello2": { 
     "name": "harjot1", 
     "fname": "harjot2", 
     "address": "noida" }, 
    "Hello3": { 
     "name": "har", 
     "fname": "har1", 
     "address": "Punjab" 
    } 
} 
+0

變化;'到'$陣列[ 「你好」 。$ i] = $ row;' – Gaurav

+0

輸出已更改,但依然在數組中擁有0,1,2,3的索引。如何刪除它們? –

+0

在屏幕截圖中顯示您的代碼。 – Gaurav

回答

1

您是具有$i聲明保持計數器但你不使用它。

更改此:

$array[] = ["Hello" => $row]; 

此:

$array["Hello".$i] = $row; 

另外補充$i++;維持和增加計數器的值。

PHP代碼:

<?php // 
$sql = "SELECT name,fname,address FROM user_management"; 
$array = array(); 

$result = $conn->query($sql); 
$i=1; 

if ($result->num_rows > 0) { 
    // output data of each row 
    $array=["message"=>"success"]; 
    while($row = $result->fetch_assoc()) { 

    $array["Hello".$i] = $row;//added line here 
    $i++;//added this line to increment counter everytime. 
} 

} 
else 
{ 
    echo "0 results"; 
} 
//echo implode(',', $array); 
// Take output array glue it with the 
echo json_encode($array); 
$conn->close(); 
?> 
+1

謝謝。真棒! –

+1

@HarjotSinghPanesar歡迎.... :) –

1

試試這個。

$i = 0; 
while($row = $result->fetch_assoc()) { 

    $array["Hello".$i++] = $row; 

} 

OR

$i = 0; 
while($row = $result->fetch_assoc()) { 

    $array["Hello".$i] = $row; 
    $i++; 
} 
+1

謝謝老兄,再次真棒! –

0

嘗試從`$陣列[] = [ 「你好」=> $行]本

if ($result->num_rows > 0) { 
    // output data of each row 
    $array=["message"=>"success"]; 
    $index = ""; 
    while($row = $result->fetch_assoc()) { 
     $array["Hello" . $index] = $row; 
     $index = $index ? ($index + 1) : 1; 
    } 
}