繁体   English   中英

PHP为什么无法访问此关联数组值?

[英]PHP Why can't I access this associative array value?

我有以下代码,并且一旦提取了CSV文件。 数组中的那个键周围有双引号。 我不确定该怎么做,所以我把他们排除在外,以为这可以让我简单地将$ array [0] ['Name']放入字符串中。 但不是! 没有。 它只是保持空白。

//获取文件并将其打开为变量

$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) "myemail@email.com"
    ["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

所以,好像

 reset($returnVal[0]);

是我的问题的答案,reset函数给了我我数组的值。 但是我仍然想知道为什么无法正常访问该元素。

您在注释中说rmove double quotes from array key但实际上并没有这样做。 该代码不起作用。 您可以在var_dump的示例输出中看到,键没有被引用,但是在示例输出中被引用了。

fgetcsv应该删除括号内的引号,这意味着您的csv文件被双引号了(可能是正确的)或其他情况。 您可以使用$returnVal[0]['"Name"']访问您的媒体资源

要实际删除键,您可能应该foreach标题行并设置str_replace或手动trim每个键并将其设置为$ header变量。 像这样:

$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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM