многомерный массив php flat-file - PullRequest
0 голосов
/ 18 февраля 2012

Я обновляю способ работы моего сайта, я уже интегрировал скрипты 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 -->

Я знаю, что это может показаться сложным способом обхода вещей, но таким образом мой сайт будет на 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 перечислял по датам, указанным в каждом текстовом файле,в настоящее время он перечисляет в алфавитном порядке из имен файлов ...

Ответы [ 3 ]

1 голос
/ 18 февраля 2012

Если вы хотите количество файлов в каталоге, вы можете попробовать это:

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;
}
1 голос
/ 18 февраля 2012

Заимствовал немного кода 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, поскольку это намного проще, безопаснее и эффективнее, чем использование простого текстового файла.

0 голосов
/ 18 февраля 2012

Я на самом деле не совсем уверен, правильно ли я понял вашу проблему. Но в конце вы хотите сохранить вложенный массив $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"));
...