[英]Always get an empty array in foreach loop
數據庫表“系統”中有兩列。 我有systemId
並想獲取mobileSystemId
。 但是我已經定義為global的變量$mobileSystemId
始終為空。
編輯:現在array_map不起作用。 我總是得到我的異常輸出“ Arrayfehler ArrayMap”,我有以下代碼:
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
在這種情況下,在函數中使用return
會更簡潔。 與您的問題無關,但是您的$systemId
var是否受信任? (以防止SQL注入)。
更新:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
應該閱讀(經過檢查;對我有用):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
我通過基於輸入返回一個虛擬值來進行嘗試; 如果對您不起作用,則數據庫中一定有一些奇怪的東西。
(更新:以下文本是您的原始代碼,未使用數組映射)
您的代碼應該按原樣工作。 您將多個$mobileSystemId
放入單個$mobileSystemId
。
它的工作原理:我用一個更簡單的代碼進行了測試,刪除了數據庫調用,但保留了您的代碼和拼寫,沒有任何改動。
因此,該錯誤必須在其他地方。 我猜想此代碼將包含在其他內容中,並且:
$mobileSystemIds = array();
聲明多次執行,從而丟失其所有數據; $mobileSystemIds = array();
聲明本身包含在更局部的范圍內 ,您可以從外部讀取它,讀取一個空值或完全不同的值。 嘗試將代碼的第一部分替換為:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
並且,在函數主體中:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.