magicbennie
magicbennie

Reputation: 523

Arrays inside array to hold filenames

This is for the front page of a website, which is supposed to display the newest/latest post at the very top, as you scroll down and goto the next pages, the posts get older.

There is a folder the contains lots of ini files with only numbers in the names. What i'm trying to do is load all the posts names (and only names - not their contents) into an array then sort those out to other arrays. I thought maybe using a multidimensional array would be a good idea. For example (if im understanding this right), $usePage[1][2] would have the number of the second post on page one. Is even the best way to do this?

Here is the relevant bit of code:

$ppp = 4;
$totalposts = 0;
$posts = array();
foreach (scandir($postsLoc) as $file) {
        if (is_file($postsLoc . "/" . $file)) {
        $totalposts++;
        array_push($posts, $file);
    }
}
natsort($posts);
array_values($posts);
$posts = array_reverse($posts);
print_r($posts);
$currPage = -;
$usePage = array(array());
$done = 0;
for ($i = $totalposts; $i != 0; $i--){
    if ($done >= $ppp){
        //Next page
        $currPage++;
        $done = 0;
        $usePage[$currPage] = array();
    }
    $done++;
    array_push($usePage[$currPage][$done], $i);
}
print_r($usePage);

So far, I've managed to confuse myself.

Thanks for any help in advance!

Upvotes: 0

Views: 44

Answers (1)

Dave F
Dave F

Reputation: 180

the below code results in a multi dimenstional $postsInPage array, the first dimension being the page ref, the second being the posts for that page. You should then be able to use this array pull out the relevant posts dependant on your pageId:

Array
(
    [1] => Array
        (
            [0] => .
            [1] => ..
            [2] => email_20131212_2c7a6.html
            [3] => email_20131212_98831.html
        )

    [2] => Array
        (
            [0] => errFile_20140110_940ad.txt
            [1] => errFile_20140110_2021a.txt
            [2] => errFile_20140110_2591c.txt
            [3] => errFile_20140110_43280.txt

etc, etc. The code (haven't included the is_file check)

// load all the posts into an array:
$allPosts = array();
foreach (scandir("temp") as $file) {
        $allPosts[] = $file;
}

//sort the array (am making an assumption that $file structure will natsort sensibly
natsort($allPosts);
$allPosts = array_values($allPosts);

//split into posts per page.
$ppp = 4;
$pageId = 1;
$totalposts = 1;
$postsInPage = array();
foreach ($allPosts as $post) {
    $postsInPage[$pageId][] = $post;
    if (($totalposts % $ppp) == 0) { //i.e. 4 per page
        $pageId++;
    }
    $totalposts++;
}

Upvotes: 1

Related Questions