我有下面的代碼,一旦我拉入CSV文件。陣列中的一個鍵有雙引號。我不知道該怎麼做,所以我剝去了它們,認爲這將允許我簡單地放$ array [0] ['Name']來訪問字符串。但不是!沒有。它只是一直空白。PHP爲什麼我不能訪問這個關聯數組值?
//獲取文件並將其打開到一個變量
$file = fopen('my.csv', 'r') or die('Unable to open file!');
//設定數組中返回數據
$returnVal = array();
//設置標題變量
$header = null;
// loop through data
while(($row = fgetcsv($file)) !== false){
// make the header array (key)
if($header === null){
echo "<pre>";
//print_r($row);
$row[0] = trim(str_replace('"', '', $row[0])); // rmove double quotes from array key
//echo "<br>".$row[0];
print_r($row);
$header = $row;
continue;
} // end of set header
//get just names and echo them
//echo "<br>".$row[0];
// more row by row column by column and set data to correct header
$newRow = array();
// loop rows and set data
for($i = 0; $i<count($row); $i++){
$newRow[$header[$i]] = $row[$i];
//echo "<br>" . $newRow[$header[$i]];
//$newRow['First_Name'] = $row[$i];
//unset($returnVal['"Name"']);
}// end for loop
$returnVal[] = $newRow;
}// end while loop
//關閉csv文件
fclose($file);
// $ returnVal現在包含CSV文件的內容
echo "Name: ".$returnVal[0]['Name'] . "<br>";
echo "Email: ".$returnVal[0]['Email Address'];
echo "<pre>";
print_r($returnVal);
// echo $returnVal[0]["Name"];
//var_dump($returnVal);
*****************編輯********* *****************
的var_dump的樣本輸出(print_r的具有相同的輸出)
array(13500) {
[0]=>
array(5) {
["Name"]=>
string(10) "my name"
["Email Address"]=>
string(19) "[email protected]"
["Date Added"]=>
string(19) "2017-03-27 03:38 PM"
["Signup Date"]=>
string(10) "2016-04-04"
["Username"]=>
string(27) "myusername1459752576"
}
echo "Name: ".$returnVal[0]['Name'] . "<br>"; // prints nothing
echo "Email: ".$returnVal[0]['Email Address']; // prints email just fine
print_r打印什麼?知道這將是非常有用的! – ksjohn
並且代碼可以壓縮爲http://sandbox.onlinephpfunctions.com/code/99034fe87c8cd7ec83219f55abdd2a63663b1588 – AbraCadaver
echo「Name:」.gettype($ returnVal [0] ['Name'])。「
」; Echo的「NULL」如果有幫助。不知道爲什麼print_r和Var_dump將其打印出來時爲空 – ThomasC