【问题标题】:multidimensional array php flat-file多维数组php平面文件
【发布时间】:2012-02-18 16:28:22
【问题描述】:

我正在升级我的网站运行方式,我已经在页面中集成了 mant php 脚本,但我正在尝试开发完全基于 php 的网站,例如,而不是加载 url:

url/events/event-1
url/events/event-2

^^^ 2 个单独的页面

我正在尝试加载

url/event?url=event-1

这样我可以更新 1 个页面,但根据

加载不同的内容
$_GET['url']

参数.....

到目前为止我所拥有的......

我加载 url/event?url=dance

它会自动在目录中搜索文件名“dance.txt”

如果文件不存在,则转发到主事件页面(url/events)

如果文件确实存在,它会创建一个关于事件的单行字符串......

文件内容如下:

Dance::::18-02-2012::::http://{external link}::::Event Information

我为导入这些数据并显示它而开发的脚本,工作正常,但我需要一个页面,将所有事件加载到一个单独的 div 中......

如果我能弄清楚如何将事件数组数据排列成所有事件的多维数组,那么制作这个页面就足够简单了......

对于单个事件,脚本简单地将变量定义为:

$name, $date, $link, $writeup

我附上了我如何做到这一点的示例代码...

    $dir    = '/server/htdocs/data/';     // path to dir with all event txt files in
$files = scandir($dir);

$fruit = array_shift($files);

$fruit2 = array_shift($files);    // array shifts remove values of '.' and '..'

$line = implode(" ",$files);    // back into string for str_replace

// echo $line;

$oldword = ".txt";

$newword = "";

$newline = str_replace($oldword, $newword, $line);

// echo $newline;


$files = explode(" ", $newline); // array of filenames

if (in_array($url, $files)) {
  $contents = file_get_contents('data/'.$url.'.txt');
} else { header('Location: http://{url}/events'); }

$info = explode('::::', $contents);

// print_r($info);

$name = $info[0];

$date = $info[1];

$link = $info[2];

$writeup = $info[3];

这对单个页面非常有效,但是,我需要一个这样的数组:

$events = array ( array ( Name => event-1,
                          Date => date-1,
                          Link => link-1,
                          Writeup => event-info ),

                  array ( Name => event-2,
                          Date => date-2,
                          Link => link-2,
                          Writeup => event-info ),

                  array ( Name => event-3,
                          Date => date-3,
                          Link => link-3,
                          Writeup => event-info )
                        );

这就是我假设数组的形成方式,但我需要脚本来计算 /data/ 文件夹中有多少文件,然后(我假设)有一个 foreach 循环,以便每个数组(事件)我可以回声:

<div id="content2"> 
                    <div class="post">
<center><h2><u>'.$name.' ('.$date.')</u></h2></center>
                       <p class="postmeta"></p>
                        <div class="entry">

<CENTER><img src="events/posters/'.$name.'.jpg" height="400" width="500"></center>

<p><p>

<p>'.$writeup.'</p>

<p><a href="'.$link.'" " target="_blank">'.$name.' Online</a></p>


 </div>
                    </div><!-- post --> 
                </div><!-- content2 -->

我知道这似乎是一种复杂的处理方式,但这样我的网站将可以通过 txt 文件中的数据 100% 编辑,因为现在我必须克隆现有页面,然后重新写入其中的所有内容参加新活动!

foreach($files as $key => $value) {

$array[] = array(explode('::::',(file_get_contents('data/'.$files[$key].'.txt'))));

}

print_r($array);

给我:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => 5th-Element
                    [1] => 11-02-2012
                    [2] => http://www.5thelementrocks.co.uk/
                    [3] => 5th Element are a 5 piece classic rock covers band gigging in venues across the North-West and Wales. Our set lists include tracks by all the greats, including AC/DC, The Cult, Muse, Bon Jovi, Nirvana, Whitesnake, The Darkness, Ozzy Osbourne, and many more. </p><p>We are a high quality, high energy, experienced classic rock band who work hard and play hard to get the audience going and to make sure each gig is a pro performance. Whether were playing for a crowd of one or one thousand, we always give 110% to keep you shakin all night long!
                )
        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => BBGM
                    [1] => 25-02-2012
                    [2] => http://nwb.co/bbgm
                    [3] => BBGM are four 40-50 something musicians (twin guitars, vocals, bass & drums) who were all in various bands years ago, playing and touring all over the North of England & Europe in the 1980s including working and recording with the now legendary producer Gil Norton.</p><p>In 2007 they got together to form BBGM to gig again. Now an established band on the Northwest circuit we are currently gigging throughout the North West and North Wales playing classic rock covers from the 70's 80's and 90's throwing in one or two original tracks penned over the years.
                )
        )

    [2] => Array
        (
            [0] => Array
                (
                    [0] => Plastic-Sarcasm
                    [1] => 18-02-2012
                    [2] => http://www.facebook.com/pages/PLASTIC-SARCASM/284242054943613?sk=info
                    [3] => Four lads who are still burning. Having the desire to kick ass every now and then through the music they create.</p><p>Originally formed in 1978 by current member Phil Narayan together with Paul Wynne, Phil Tonge and Baz Yates, the Band played in the Punk Rock scene era in and around Bolton. Having not played guitar (but played drums for a couple of years from 1986 1989) on stage for over thirty years, Phil Narayan couldn't resist a late urge to enjoy the feeling of playing live on stage once again. Regularly practising with PLUM ( joined the band as singer in 1980) who, now plays Bass guitar and sings, the pair set about making the dream happen once again. They recruited Gordon Connolly for an extra guitar who has been playing throughout his life with various bands, in September 2010. Finally, drummer Gag Martin joined up in reply to an advert at the local rehearsal studios in May 2011.</p><p>"Having had 9 practice / Jammin sessions the band played their first gig in Little Lever on 17th December 2011 where all the old Punk songs were revived. The gig was a screaming success and it is the intention to do more gigs in 2012 when the band will gradually introduce their own numbers more and more as gigs go by."
                )
        )

    [3] => Array
        (
            [0] => Array
                (
                    [0] => Whipcord
                    [1] => 17-02-2012
                    [2] => http://www.facebook.com/whipcord
                    [3] => Doobie Brothers in Bad Brains t-shirts, whistling The Hollies on the way to a Pentagram gig, reading The Wire...it's rock n roll!!</p><p>Whipcord are a stentorian rock n roll power trio from Salford, Manchester UK. Within the noise is a classicist rock feel, drowning in a tar pool of punk rock fury. Being described as the bastard child of Motorhead and Foo Fighters. and that of polished anarchy, not unlike The Whos live shows.
                )
        )
)

啊哈几乎完成了。

ps 我希望 foreach 按每个 txt 文件中规定的日期列出,它目前按文件名的字母顺序列出...

【问题讨论】:

  • +1 表示花了这么多时间在一个问题上。
  • 你知道这会比 DB 慢得多吧?!可能的编码问题等等......只是说
  • 我明白,但我不能使用 db,由于某种原因 mysql 不会安装在我的机器上,但我还是更喜欢 txt 文件,因为这样更安全:).....
  • 我试图访问甚至不存在的数据库的狡猾的中国机器人的数量,它在平面文件上更安全,我假设为每个事件将数据加载到每个数组中将是一个简单的 file_get_contents ,但我不确定如何实现
  • @DJ-P.I.M.P 说平面文件比 mysql 更安全,这是一个非常笼统的说法。有同样多的机器人(如果不是更多的话)试图通过 ssh 或远程访问您的服务器以访问您的文件。

标签: php multidimensional-array flat-file


【解决方案1】:

借用了一点 Jribeiro 的代码,将文件实际读入二维数组。

$items = array();
if ($handle = opendir($dir)) {
    while (false !== ($file = readdir($handle))) {
        $fp = fopen("$file","r");

        while($line = fgets($fp)){
            $parts = explode("::::",$line);
            $newArr["Name"] = $parts[0];
            $newArr["Date"] = $parts[1];
            $newArr["Link"] = $parts[2];
            $newArr["Writeup"] = $parts[3];
            $items[] = $newArr;  // add newArr to items
        }
        fclose($fp);
    }
    closedir($handle);
}

print_r($items);

然后,循环遍历$items 数组:

foreach($items as $item){
    $name = $item["Name"];
    echo "Name is $name<br>";
    // etc
}

不过,我需要通知您考虑使用 MySQL 来执行此操作,因为它比使用纯文本文件更容易、更安全且更强大。

【讨论】:

  • 这看起来很有希望,但是每个事件都有一个不同的.txt文件,因为我需要在加载动态页面时搜索文件名,如果文件名不存在,它会转发到另一个页面
  • 感谢您抽出宝贵时间回答您,也许还有另一种方法可以为多个文件编写此内容,
  • 我确实尽可能多地解释了大声笑,我一直在绞尽脑汁想弄清楚如何表达这个表达方式以及它背后的逻辑
  • 但我非常感谢我得到的任何帮助
  • print_r($items) 显示一个空数组,所以 foreach 现在没有做任何事情,但是我知道 foreach 会工作,然后数组 $items 已经填充了值
【解决方案2】:

如果你想要 dir 中的文件数,你可以试试这个:

function fileCounter($dir){
    $counter = 0;
    if ($handle = opendir($dir)) {
      //echo "Directory handle: $handle\n";
      //echo "Files:\n";
      /* This is the correct way to loop over the directory. */
      while (false !== ($file = readdir($handle))) {
          //echo "<BR>".$counter." - $file";
          $counter++;
      }
      closedir($handle);
    }
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1
    return $counter;
}

【讨论】:

  • 我今天已经编写的代码在它自己的数组中列出了所有文件名,并删除了“。”和 '..' 我已经使用了 func $count = count($files)
  • 所以如果我需要一个有多少事件的变量,我可以从技术上计算数组值的数量.....但是我无法将每个文本文件数据添加到数组中,所以我可以遍历每一个并从每个输出数据
  • 哦,对不起,误解了...看来上面的答案是正确的。我稍后会检查是否解决了这个问题:)
【解决方案3】:

我实际上不太确定我是否正确理解了您的问题。 但最后你想将嵌套数组$events 存储在平面文件中并将其读回数组? 我建议使用serialize 来做到这一点,那么它很简单:

$events = array ( array ( Name => event-1,
                          Date => date-1,
                          Link => link-1,
                          Writeup => event-info ),

                  array ( Name => event-2,
                          Date => date-2,
                          Link => link-2,
                          Writeup => event-info ),

                  array ( Name => event-3,
                          Date => date-3,
                          Link => link-3,
                          Writeup => event-info )
                        );
file_put_contents("/foo/bar",serialize($events)); // BAM, it's in the file :)
//reading it back is equally simple
$events2 = unserialize(file_get_contents("/foo/bar"));

【讨论】:

  • 不抱歉,我在一个文件夹中有几个平面文件,每个文件都有一个事件的文件名,每个文件中都有每个事件的详细信息.....我需要读取和输出每个 txt文件详细信息,按最早日期到最远日期排序,并输出每个文本文件详细信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2020-06-06
  • 1970-01-01
相关资源
最近更新 更多