Ivan
Ivan

Reputation: 2481

Getting parent key in a nested array

I'm building a "nested" array fetching from database; here's my script:

while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
    $numbers[] = array("Page ");
}

I'd like to obtain the following array (with print_r() function), but I'm totally stuck on how to get the page number:

Array
(
    [0] => Array
        (
            [0] => Page 1
            [1] => 1
        )

    [1] => Array
        (
            [0] => Page 2
            [1] => 2
        )

    [2] => Array
        (
            [0] => Page 3
            [1] => 3
        )


    [3] => Array
        (
            [0] => Page 4
            [1] => 4
        )

)

I tried:

$numbers[] = array("Pagina " . key($numbers)+1, key($numbers)+1);

but it didn't lead to expected results (in my mind, it should get the current key number of the "parent" array and increment by 1).

Upvotes: 0

Views: 506

Answers (2)

datacompboy
datacompboy

Reputation: 301

Just count by your own:

$n = 0;
while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
    $n++;
    $numbers[] = array("Page ".$n, $n);
}

Or, use count($numbers)+1 in your code:

while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
    $numbers[] = array("Page ".(count($numbers)+1), count($numbers)+1);
}

Upvotes: 2

Ivan
Ivan

Reputation: 2481

Thanks to datacompboy I finally came to this:

while ($row_rsMaster = mysql_fetch_assoc($rsMaster)) {
    $counter = count($numbers)+1;
    $numbers[] = array("Page " . $counter, $counter);
}

Upvotes: 0

Related Questions