2017-08-04 111 views
0

我有下面的代碼,一旦我拉入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 
+2

print_r打印什麼?知道這將是非常有用的! – ksjohn

+0

並且代碼可以壓縮爲http://sandbox.onlinephpfunctions.com/code/99034fe87c8cd7ec83219f55abdd2a63663b1588 – AbraCadaver

+0

echo「Name:」.gettype($ returnVal [0] ['Name'])。「
」; Echo的「NULL」如果有幫助。不知道爲什麼print_r和Var_dump將其打印出來時爲空 – ThomasC

回答

0

所以,它看起來像

reset($returnVal[0]); 

是我的問題的答案,重置函數爲我提供了我的數組值。但我仍然想知道爲什麼對元素的正常訪問不起作用。

0

你說在評論rmove double quotes from array key,但你實際上並沒有這樣做。該代碼不起作用。您可以在var_dump的示例輸出中看到,鍵未被引用,但是在您的示例輸出中。

fgetcsv應刪除封閉的引號,這意味着您的csv文件是雙引號(這可能是正確的)或其他事情正在進行。你可以用$returnVal[0]['"Name"']

訪問你的財產要真正刪除鍵,你或許應該foreach標題行和手動每個鍵設置str_replacetrim,並將其設置爲$頭變量。類似這樣的:

$header = array(); 
foreach($row as $key => $value) { 
    $key = trim($key, "\" \t\n\r\0\x0B"); // trim quotes as well as standard trim characters 
    $header[$key] = $value; 
} 
相關問題