2014-10-09 57 views
1

以下PHP代碼只轉換的值,但我還需要的關鍵的每個值:JSON響應唯一值,但關鍵+值所需

應如何將它(期望輸出):

[{"ID":"1","styleNo":"1","styleName":"Casual","placeholder":"Left Initial","type":"text","maxlength":"1","size":"small","position":"1"},{"ID":"2","styleNo":"1","styleName":"Casual","placeholder":"Right Initial","type":"text","maxlength":"1","size":"small","position":"2"},{"ID":"3","styleNo":"1","styleName":"Casual","placeholder":"Center Initial","type":"text","maxlength":"1","size":"small","position":"3"}] 

它是如何實際上是(我不知道羯羊不同的支架有關係嗎?):

[["1","1","Casual","Left Initial","text","1","small","1"],["2","1","Casual","Right Initial","text","1","small","2"],["3","1","Casual","Center Initial","text","1","small","3"]] 

<?php 
$style = $_GET['style']; 
define('HOST', 'localhost'); 
define('USER', 'root'); 
define('PASS', ''); 
define('DBNAME', 'inscribe'); 

$db = new mysqli(HOST, USER, PASS, DBNAME); 

if (mysqli_connect_errno()) { 
    printf("Connect failed: %s<br/>", mysqli_connect_error()); 
} 

$sql = "SELECT * FROM inputs WHERE styleNo = '".$style."'"; 
$result_db = $db->query($sql); 
$all_result = $result_db->fetch_all(); 
echo json_encode($all_result); 
$db->close(); 
?> 
+1

所以最新的問題?在編碼後'$ all_result'看起來像什麼? – Ghost 2014-10-09 01:03:32

+0

它看起來像上面的「實際上是如何」部分,只是打印值,但不是像ID,styleNo,styleName這樣的鍵...... – Marius 2014-10-09 01:09:01

回答

3

嘗試明確設置了MySQL中獲取fetch_all()標誌MYSQLI_ASSOC因爲它的默認值是MYSQLI_NUM它返回數字指數,而不是關聯。

例子:

$all_result = $result_db->fetch_all(MYSQLI_ASSOC); 
echo json_encode($all_result); 

旁註:要麼逃脫輸入或使用準備好的語句:

$style = $db->real_escape_string($_GET['style']); 
$sql = "SELECT * FROM inputs WHERE styleNo = '$style' "; 
$result_db = $db->query($sql); 
$all_result = $result_db->fetch_all(MYSQL_ASSOC); 
echo json_encode($all_result); 

或者

$sql = "SELECT * FROM inputs WHERE styleNo = ?"; 
$select = $db->prepare($sql); 
$select->bind_param('s', $_GET['input']); 
$select->execute(); 
$result = $select->get_result(); 
$all_result = $result->fetch_all(MYSQL_ASSOC); 
echo json_encode($all_result); 
+0

這樣做,謝謝! – Marius 2014-10-09 01:16:34

+0

@Marius im很高興這有幫助 – Ghost 2014-10-09 01:19:06

-1

它做它應該。 SQL查詢返回結果行,這就是它給你的東西。快速修復將是

$tmp = array(); 
$keys = array("ID", "styleNo", "placeholder", "type", "maxlength", "size", "position"); 
foreach($all_result as $row){ 
    $tmp[] = array_combine($keys, $row); 
} 

echo json_encode($tmp); 

如果您選擇的變化這可能會中斷。

相關問題