![](/img/trans.png)
[英]Creating an associative array from Wordpress $wpdb->get_results
[英]How to remove the extra array from wpdb->get_results
我有一個數組:
$location= $wpdb->get_results("
SELECT
town, county, country
FROM
" . $wpdb->prefix . "table WHERE ID = " . $ID);
這只會返回一行,因為 ID 是唯一的。
我需要將這些數據放入一個數組中,所以它看起來像:
array("Base" => $basetype,
"Fields" => array("town"=>"Birmingham", "county"=>"West Midlands", "country"=>"UK"))
如果我對這一行進行硬編碼,則 API 可以工作,但如果我嘗試使用:
array("Base" => $basetype,
"Fields" => $location
我似乎添加了一個我不想要的額外數組:
Array ( [Base] => test [Fields] => Array ( [0] => Array ( [Town] => Birmingham [County] => West Midlands [Country] => UK
如何避免這個額外的數組( => Array ( [0]
)?這是 WordPress 特有的嗎?我嘗試更改get_results
的格式,但無濟於事。
您可能知道 SQL 只會返回一行,但您的代碼不會! get_results
返回所有匹配的行,即一個行數組(作為 arrays 或對象) - 即使結果只是一行,它仍然在數組中返回它。
1 - 使用get_row
只返回一行
您可以使用get_row
只返回一個結果,例如:
$location = $wpdb->get_row("SELECT town, county, country FROM "
. $wpdb->prefix . "table WHERE ID = " . $ID,
ARRAY_A);
請注意,您應該在get_row
中使用ARRAY_A
以確保該行作為關聯數組返回。
2 - 返回所有行(並且只使用第一個結果)
根據使用此代碼的位置,您可能希望代碼繼續返回一個數組,以便它與您使用它的其他地方兼容。 您可以按如下方式執行此操作:
首先,在get_results
中使用ARRAY_A
以確保將行作為關聯數組返回:
$locations = $wpdb->get_results("SELECT town, county, country FROM "
. $wpdb->prefix . "table WHERE ID = " . $ID,
ARRAY_A);
2a - 只使用代碼中的第一行:如您所知,您只有一行,您只需要從查詢返回的數組中獲取第一個結果:
$first_location = $locations[0];
現在$first_location
包含第一行(也是唯一的),因此您可以在代碼的 rest 中使用它(或者您可以直接使用$locations[0]
)。
2b - 遍歷所有行(即使它只是一個行):如果您還需要此代碼可重用,您可以遍歷結果並單獨處理每一個。 當您的結果只有一行時,循環將只運行一次,例如:
foreach ($locations as $location){
// Do your stuff here, using $location as before...
// If you only have one result, then the loop will only run once
}
參考
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.