将数据从文本文件复制到php数组

时间:2018-05-08 04:15:06

标签: php

我有一个文本平面文件data.txt,其中包含此特定格式的数据,并且它始终相同:

id: 24153
firstname: john
lastname: smith
registered: true
id: 27663
firstname: ben
lastname: jackson
registered: false

如何读取文本文件并循环遍历所有数据点,以生成包含以下列方式排列的所有数据的单个数组:

Array
(
    [0] => Array
        (
            [id] => 24153
            [firstname] => john
            [lastname] => smith
            [registered] => 1
        )

    [1] => Array
        (
            [id] => 27663
            [firstname] => ben
            [lastname] => jackson
            [registered] => 
        )

)

我的未完成/失败尝试。我可以把它全部放在一个数组中,但不知道如何以所描述的方式格式化它。

$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$arr = array();
foreach ($lines as $line_num => $line) {
    if (strpos($line, 'id') !== false) {
        $arr[$line] = //not sure how to move forward from here
    }
}

4 个答案:

答案 0 :(得分:2)

选项1:如果id始终是该组的第一行,则只需使用1个循环即可执行更简单的方法。

使用array_values会将关联数组转换为简单数组。

$fh = fopen('newfile.txt','r');
$result = array();
while ($line = fgets($fh)) {
    $line = trim($line);
    if ( $line !== '' ) {
        $line = explode(":", $line, 2);
        if ( trim( $line[0] ) === 'id' ) $id = trim( $line[1] );
        $result[$id][trim( $line[0] )] = trim( $line[1] );
    }
}
fclose($fh);

echo "<pre>";
print_r( array_values($result) );
echo "</pre>";

选项2:您可以通过文件的每一行使用循环。数组块。并使用array_reduce格式化数组。

$fh = fopen('newfile.txt','r');                                //Open file
$arr = array();
while ($line = fgets($fh)) {                                   //Loop thru each line
    $arr[] = trim($line);                                      //Trim the line and push in array
}
fclose($fh);

$arr = array_chunk( $arr, 4 );                                  //chunk array in the size of 4

//use array_reduce to format the array Format array
$result = array_reduce($arr, function($c,$v){
    $temp = array();
    $id = "";

    foreach($v as $val) {
        $val = explode(":", $val, 2);
        $temp[ trim( $val[0] ) ] = trim( $val[1] );
    }

    $c[$id] = $temp;
    return $c;
},array());

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [24153] => Array
        (
            [firstname] => john
            [lastname] => smith
            [registered] => true
        )

    [27663] => Array
        (
            [firstname] => ben
            [lastname] => jackson
            [registered] => false
        )

)

答案 1 :(得分:1)

最简单的方法是使用array_chunk()foreach()explode()

<?php


$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$chunk_array = array_chunk($lines,4);

$arr = array();
$key = 0;
foreach ($chunk_array as $line_num => $line) {

   foreach($line as $l){
       $exploded_array = explode(':',$l);
       if(trim($exploded_array[0]) =='id'){
           $key = trim($exploded_array[1]);
       }else{
           $arr[$key][trim($exploded_array[0])] = trim($exploded_array[1]);
       }
   }
}
echo "<pre/>";print_r($arr);

输出: - https://prnt.sc/jf3zh5

对于您更改的要求,请执行以下操作: -

<?php


$lines = file('data.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

$chunk_array = array_chunk($lines,4);

$arr = array();
foreach ($chunk_array as $line_num => $line) {

   foreach($line as $l){
       $exploded_array = explode(':',$l);
       $arr[$line_num][trim($exploded_array[0])] = trim($exploded_array[1]);
   }
}
echo "<pre/>";print_r($arr);

答案 2 :(得分:0)

请使用此代码。这是经过测试的代码,可以根据需要正常工作。在此脚本中,不需要额外的循环。我们只需使用if and else

即可实现
<?php
if ($file = fopen("file.txt", "r")) {
        $dataArray = array();
        $newline = '';
        $id = '';
    while(!feof($file)) {
        $line = fgets($file);
        # do same stuff with the $line
        if (strpos($line, "id:") !== false) {
            //print_r($line);echo '</br>';
            $id_line = explode(":",$line);
            $id = $id_line[1];
        }else{
            if(!empty($id)){
                $new_line = explode(":",$line);
                $dataArray[$id][$new_line[0]] = $new_line[1];
            }
        }



    }
    fclose($file);
}
echo '<pre>';
print_r($dataArray);
?>

输出:

Array
(
    [ 24153] => Array
        (
            [firstname] =>  john

            [lastname] =>  smith

            [registered] =>  true

        )

    [ 27663] => Array
        (
            [firstname] =>  ben

            [lastname] =>  jackson

            [registered] =>  false
        )

)

答案 3 :(得分:0)

我宁愿使用array_map和array_filter来最小化循环。我尝试过简单的字符串操作,你可以使用fopen。

解释包含在下面的评论中

$str="id: 24153
firstname: john
lastname: smith
registered: true
id: 27663
firstname: ben
lastname: jackson
registered: false";
//explode by new line
$arr=explode("\n",$str);
//take the value only,OP is saying format is same
$arr1=array_map(function ($a) { return str_replace(":","",strstr($a, ':')); }, $arr);
//remap the value if index is divisible by 4 , that is if it is id, remember the format is fixed
$arr2=array_values(array_filter(array_map(function ($a,$k)use($arr1) { if($k%4==0) { return array($a=>array('firstname'=>$arr1[$k+1],'last_name'=>$arr1[$k+2],'registered'=>$arr1[$k+3]));} else {return null;} }, $arr1,array_keys($arr1))));
echo "<pre>";
print_r($arr2);

输出

Array
(
    [0] => Array
        (
            [ 24153] => Array
                (
                    [firstname] =>  john
                    [last_name] =>  smith
                    [registered] =>  true
                )

        )

    [1] => Array
        (
            [ 27663] => Array
                (
                    [firstname] =>  ben
                    [last_name] =>  jackson
                    [registered] =>  false
                )

        )

)

工作小提琴:http://phpfiddle.org/main/code/6n5g-bvpx