PHP —— 读取文件到二维数组

转自:PHP读取自定义ini文件到二维数组

读取文件,可以使用file_get_contents,file,parse_ini_file等,现在有一个需求,需要读取如下格式的文件:

 1 [food]
 2 apple
 3 meat
 4 [tool]
 5 linux
 6 $
 7 $_GET[]
 8 `
 9 '
10 "
11 {
12 }
13 -
14 =
15 
16 /
17 ?
18 
19 <
20 .

这种格式类似ini文件,但是读取的时候只能读取到第一维度,第二维度读不出数据,没办法,只能自己写了

<?PHP

    function getArr( $file ){
        if(!file_exists( $file )){
            return false;//判断文件是否存在
        }
        $res = array();
        $key = '';
        $arr = file( $file );
        foreach($arr as $value){
            $value = trim( $value );
            if( empty($value)){
                continue;//去除空行
            }
            if( preg_match( '/^[(.+)]$/', $value, $temp) ){
                $key = $temp[1];//确定第一维度
                continue;
            }
            $res[$key][] = $value;//确定第二维度
        }
        return $res;
    }
    print_r(getArr('config.ini'));//文本文件
    
?>

输出结果:

 转自:PHP读取自定义ini文件到二维数组

原文地址:https://www.cnblogs.com/picaso/p/3473965.html