从一个文件中读取多个数据,PHP

时间:2017-11-12 16:39:32

标签: php file web

我有这个文本文件,我想阅读并检查值是否正确,然后显示在html文件中:

Audi, 2006
BMW, 2019    //date incorrect
Toyota, 2016
Frd, 2017    //name incorrect 

我所做的一切都是:

$handle = file('src/can.txt');
$data = array();      
//loop to get the value from handle                                                
foreach ($handle as $key ) { 
  array_push($data, $key);
}

我想继续使用另一个循环,我在其中创建2个数组,然后使用explode方法将汽车名称与生产年份分开。

我的问题是:是否有任何构建PHP方法或更好的方法来执行相同的操作?

1 个答案:

答案 0 :(得分:0)

我建议使用重复动作的方法。这是一个例子,建议你处理品牌/品牌的案例敏感度。

我还会保留数组索引以便于参考。

<?php
    class File {

        private $_minYear = 2000,
                $_maxYear = 2018,
                $_brand = array('BMW','Audi','Toyota','Ford');

        private function validateYear($year) {
            $year = (int)$year;
            return ($this->_minYear < $year && $year < $this->_maxYear);
        }

        public function scan($file) {
            $lines = file($file);                                                  
            foreach ($lines as $key => $value) {
                $data = explode(',',$value);
                if (in_array($data[0], $this->_brand) && $this->validateYear($data[1])) {
                    $records[$key] = $value;
                } else {
                    $errors[$key] = $value;
                }
            }
            return array('records' => $records, 'errors' => $errors);
        }
    }

    $file = new File;

    $data = $file->scan('testcar.txt');

    echo '<pre>';

    print_r($data['records']);

    print_r($data['errors']);

输出:

Array
(
    [0] => Audi, 2006

    [2] => Toyota, 2016

)
Array
(
    [1] => BMW, 2019

    [3] => Frd, 2017
)

不使用Class / Method

<?php

$brands = array('BMW','Audi','Toyota','Ford');

function validateYear($year) {
    $year = (int)$year;
    return (2000 < $year && $year < 2018);
}

function fileScan($file) {
    $lines = file($file);                                                  
    foreach ($lines as $key => $value) {
            $data = explode(',',$value);
            if (in_array($data[0], $brands) && validateYear($data[1])) {
                    $records[$key] = $value;
            } else {
                    $errors[$key] = $value;
            }
    }
    return array('records' => $records, 'errors' => $errors);
}

$data = fileScan('testcar.txt');

echo '<pre>';

print_r($data['records']);

print_r($data['errors']);