dragon201401 2014-10-17 03:58
浏览 81
已采纳

从文本文件封装和读入数组

I'm trying to make 2 classes, to encapsulate these text files, Customer.txt and Orders.txt. The customer one I need to read each line into a separate instance of an array for each line of text, how can I do this? Also, do I have to do something about the comma's in the text files?

I know I need to use fopen, just not sure how to go about doing it.

This is what I've tried so far.

<?php



class readOrders{

$array_of_lines = fopen("orders.txt", 'r') or die("Failed to create file");
  foreach($array_of_lines as $line) {
 $pieces_of_line = explode(',', $line); 

}

class readCustomers{
$array_of_more_lines = fopen("customers.txt", 'r') or die("Failed to create file");
  foreach($array_of_more_lines as $line) {
 $pieces_of_line = explode(',', $line);

}


?>

Here are my text files

Orders.txt

1,4,0133360903,Building Java Programs,Computer Science
2,6,0321836995,Mathematics All Around,Mathematics
3,24,0321825721,Mathematics for Elementary Teachers with Activity Manual,Mathematics
4,10,0133011208,Business Math,Business

customers.txt

2,Leonie,Köhler,leonekohler@surfeu.de,University of Stuttgart,Theodor-Heuss-Straße 34,Stuttgart,,Germany,70174,+49 0711 2842222
3,Bjørn,Hansen,bjorn.hansen@yahoo.no,University of Oslo,Ullevålsveien 14,Oslo,,Norway,0171,+47 22 44 22 22
4,François,Tremblay,ftremblay@gmail.com,McGill University,1498 rue Bélanger,Montréal,QC,Canada,H2G 1A7,+1 (514) 721-4711
  • 写回答

1条回答 默认 最新

  • dr897777 2014-10-17 04:04
    关注

    I think fgetcsv will be useful here, example from php-doc:

    <?php
    $row = 1;
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>
    ";
            $row++;
            for ($c=0; $c < $num; $c++) {
                echo $data[$c] . "<br />
    ";
            }
        }
        fclose($handle);
    }
    ?> 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP