[英]Associative-array in PHP from CSV / TXT file
我对PHP中的关联数组有问题-数组的来源是来自文本文件的。
当我写如下内容时:
$logins = array('user1' => '1234','user2' => '2345','user3' => '3456');
一切都按预期工作。
因此,我试图像这样从CSV文件中调用这些数组:
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if (empty($line_of_text)) { break; }
$logins = array($line_of_text[0] . '=>' . $line_of_text[1]); /* remove the => and seperate the logins with "," on CSV */
}
没用
关于SO,这里有很多密切相关的问题和答案,但我确实阅读并尝试将其植入,但没有成功。 请指导我。
编辑: data.csv
如下所示。
user1,1234;
user2,2345;
user3,3456;
这就是我想你想要的
$logins = array();
$file_handle = fopen("data.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
// At this point, $line_of_text is an array, which will look
// something like this: {[0]=>'user1',[1]=>'1234'}
if (empty($line_of_text)) { break; }
$logins[$line_of_text[0]] = $line_of_text[1];
// So the line above is equivalent to something like
// $logins['user1'] = '1234';
}
尽管我认为这不是您真正想要了解的内容,但它可能也可以工作
/* $dataFile = fopen("data.txt", "r"); */
$dataFile = file_get_contents("data.txt");
/* logins = array($dataFile); */
eval('$logins = ' . $dataFile . ';');
您可以避免这些循环,条件和fopen()
/ fclose()
混乱:
<?php
// read the file into an array
$arr = file("data.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// split each line at the comma
array_walk($arr, function(&$v, $k){$v=explode(",", $v);});
// build an array from the data
$keys = array_column($arr, 0);
$values = array_column($arr, 1);
$logins = array_combine($keys, $values);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.