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条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算