【发布时间】:2018-08-18 04:01:56
【问题描述】:
我发现基本脚本中的一些(应该很简单)PHP 代码存在一个奇怪的问题。
我有一个多维关联数组 $accounts,在使用 var_dump 时看起来像这样:
Array(4) {
[0] =>
array(3) {
'account' =>
string(37) "Flood Cleanup City - Desktop - Exact "
'parameter' =>
string(23) "flood_cleanup_city_d_em"
'phone' =>
string(0) ""
}
[1] =>
array(3) {
'account' =>
string(51) "Flood Cleanup City - Desktop - Exact Call Extension"
'parameter' =>
string(3) "N/A"
'phone' =>
string(0) ""
}
[2] =>
array(3) {
'account' =>
string(38) "Flood Cleanup City - Desktop - Phrase "
'parameter' =>
string(23) "flood_cleanup_city_d_pm"
'phone' =>
string(0) ""
}
[3] =>
array(3) {
'account' =>
string(52) "Flood Cleanup City - Desktop - Phrase Call Extension"
'parameter' =>
string(3) "N/A"
'phone' =>
string(0) ""}
}
所以,很简单。该数组在函数中生成并作为返回值传递给变量 $listAccounts。
我只想遍历 $listAccounts 并提取“帐户”值,所以我写了这个:
foreach($listAccount as $account)
{
$accountName = $account['account'];
echo $accountName;
}
我希望它会输出四个帐户字符串。相反,$account['account'] 返回 NULL。但是,如果我使用 array_keys 函数从数组中提取键的名称并使用此代码,它可以正常工作:
$accountName = $account[array_keys($account)[0]];
如果可能相关,生成多维数组的函数正在使用 fgetcsv() 函数来解析 CSV 文件:
function getAccounts()
{
$handle = fopen("water.csv","r");
$header = NULL;
$accounts = array();
$n = 0;
while (!feof($handle)) {
$account = fgetcsv($handle);
if(!$header)
{
$header = $account;
}
else
{
$accounts[] = array_combine($header,$account);
}
}
fclose($handle);
echo var_dump($accounts);
return $accounts;
}
【问题讨论】:
-
您可能认为欺骗链接不相关,但它也直接相关,因为它也被忽略了。您在该文件中有一个 BOM,正在使用
fgetcsv中的第一个标题字段读取它。在进行 csv 解析之前,您需要摆脱它。