[英]How do I name an array key with a key inside the array
我有一些數據,是的。 此數據來自MySQL查詢,並且始終始終包含4個項目。 我想將該數據緩存在數組表中,以供以后在網頁中使用,但我想保留查詢中的鍵,並在多維數組中分離出每個分組。 但是,為了節省每次要查找給定數據組時遍歷數組的時間,我想將第一個數組的鍵稱為ID鍵,該鍵始終是每四個項中的第一個鍵。
目前,我正在使用以下代碼:
function mysql_fetch_full_result_array($result)
{
$table_result=array();
$r=0;
while($row = mysql_fetch_assoc($result)){
$arr_row=array();
$c=0;
while ($c < mysql_num_fields($result)) {
$col = mysql_fetch_field($result, $c);
$arr_row[$col -> name] = $row[$col -> name];
$c++;
}
$table_result[$r] = $arr_row;
$r++;
}
return $table_result;
}
我目前正在使用3個唯一用戶進行測試,因此我從查詢中返回了三行,並且此函數的數據最終以以下格式顯示:
[0]=>
. . [id] => 1
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[1]=>
. . [id] => 34
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[2]=>
. . [id] => 56
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
因此,如何更改代碼以代替鍵[0],[1],[2]給我輸出:
[1]=>
. . [id] => 1
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[34]=>
. . [id] => 34
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
[56]=>
. . [id] => 56
. . [name] => random name
. . [tel] => random tel
. . [post] => post code data
我不介意主數組鍵是數字的字符串而不是數字的字符串,但是我有點卡住了,我嘗試更改$table_result[$r] = $arr_row;
要讀取的部分$table_result[$result['id']] = $arr_row;
但這只會輸出一個人的數組。 我知道我需要另一個循環,但是我正在努力研究如何編寫它。
$arr_row[(name of ID field in your result)][$col -> name] = $row[$col -> name]
那應該將您的數組鍵設置為ID,因此應該分配,例如:
$arr_row[34]['id'] = 34;
$arr_row[34]['name'] = 'name';
$arr_row[34]['tel'] = 'tel';
$arr_row[34]['post'] = 'post';
更改行:
$table_result[$r] = $arr_row; $r++;
to
$table_result[$arr_row['id']] = $arr_row;
而且我認為您不再需要$ r。
怎么樣:
$table_result = array();
$sql = "SELECT id, name, tel, post FROM sometable";
$res = mysql_query($sql);
if (mysql_error()) {
die("MySQL error: " . mysql_error());
}
while($row = mysql_fetch_array($res)) {
$table_result[$row['id']] = $row;
}
如您所說,如果您不介意在每個數組元素中重復使用ID字段,則無需遍歷各個行並提取字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.