[英]Create multidimensional array from a loop in PHP
我正在嘗試從數據庫中的某些內容創建多維數組。
目前,我有這個,它創建了一個數組:
$js_arr = [];
while($row = mysqli_fetch_array($r->query)){
$js_arr[] = $row['todo_content'];
}
返回:
Array ( [0] => first [1] => tester [2] => first item [3] => Hello!)
但是,我還需要獲取$row['todo_id']
。
我已經嘗試過了,但是它只為第一行創建一個數組 :
$js_arr = [];
while($row = mysqli_fetch_array($r->query)){
$js_arr['todo_content'] = $row['todo_content'];
$js_arr['todo_id'] = $row['todo_id'];
}
返回:
array(2) { ["todo_content"]=> string(3) "hey" ["todo_id"]=> string(2) "90" }
我仍在學習PHP,因此非常感謝任何幫助或指針。
兩種不錯的選擇:
如果todo_id
是唯一的,則使其為鍵:
$js_arr[$row['todo_id']] = $row['todo_content'];
或者對於多維數組,如果您不只是todo_content
,還需要:
$js_arr[] = array('todo_content' => $row['todo_content'], 'todo_id' => $row['todo_id']);
我將使用ID作為密鑰:
while($row = mysqli_fetch_array($r->query)){
$js_arr[$row['todo_id']]['todo_content'] = $row['todo_content'];
}
或者-假設您需要從數據庫中獲取的所有信息:
while($row = mysqli_fetch_array($r->query)){
$js_arr[$row['todo_id']] = $row;
}
您可以替換的內容(無循環,但沒有ID作為鍵):
$js_arr = mysqli_fetch_all($r->query);
只需將所需的項嵌套在數組中:
$js_arr[] = [
'todo_content' => $row['todo_content'],
'todo_id' => $row['todo_id']
];
$js_arr[]
部分不能$js_arr[]
任何其他事情,因為任何其他語法都不會無條件地將元素添加到多維數組的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.