doudu2591 2015-03-20 14:10
浏览 38
已采纳

从文件中读取并创建关联数组?

I am able to read from a file and create an array however I get the following error: Notice: Undefined offset: 1. Within my array there is one element that is empty and I don't understand why it is empty.

My text file is in the following format:

#EXTINF:0,ABC family USA[]http://localhost/IpInfo/index.html  
#EXTINF:0,CBC[]http://localhost/IpInfo/index1.html
#EXTINF:0,A&E[]http://localhost/IpInfo/index2.html

Here is my code:

$fh = fopen('file1.txt', 'r');
$theData = fread($fh, filesize('file1.txt'));
$arr = array();
$my_array = explode("
", $theData);

foreach($my_array as $line){
    $tmp = explode("[]", $line);
    $arr[$tmp[0]] = $tmp[1];
}
fclose($fh);

echo '<pre>';
echo print_r($arr);

I'm not quite sure what the problem is? Any help would be much appreciated!

Thanks!

  • 写回答

2条回答 默认 最新

  • duanran8648 2015-03-20 14:16
    关注

    Probably your input data doesn't use as the line delimiter? I'm not sure whether I got the problem completely. Also you might want to take empty lines into account.

    I would use the file() function, which simplifies to iterate over the lines of a file and can handle Windows and Unix line feeds and check for empty lines:

    $arr = array();
    
    foreach(file('a.txt') as $line){
        // I'm using `trim()` here since $line
        // will still contain the newline delimiter
        $line = trim($line);
    
        // Skip empty lines
        if(empty($line) {
            continue;
        }
    
        $tmp = explode("[]", $line);
        $arr[$tmp[0]] = trim($tmp[1]);
    }
    
    echo '<pre>';
    print_r($arr);
    

    Output:

    <pre>Array
    (
        [#EXTINF:0,ABC family USA] => http://localhost/IpInfo/index.html
        [#EXTINF:0,CBC] => http://localhost/IpInfo/index1.html
        [#EXTINF:0,A&E] => http://localhost/IpInfo/index2.html
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题