0

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).

3
  • why are you putting the page numbers in the same array $numbers[]? Commented Apr 14, 2012 at 8:07
  • I need to json encode that array to get someting like tthat: [["Page 1", 1], ["Page 2", 2], ["Page 3", 3]] Commented Apr 14, 2012 at 8:12
  • I don't understand why your code is ignoring the actual row data in the result set, but in modern PHP (which no longer appreciates mysql_*() functions), just pass your result object to foreach() and declare the key in the signature. foreach ($rsMaster as $i => $row) { ++$i; $numbers[] = ["Page $i", $i]; } Commented Nov 30, 2024 at 7:02

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I was thinking to use a counter, but I was wondering if there's a counter-less solution... is it possible?
Well, when you get count($numbers), you still use counter. Its internal of php, but it still there.
Yeah, we are almost there!!! It's all fine with the second solution, except that the "Pagina".count($numbers)+1 gets converted in a number... mmm... strange
oh, forget for additional brackets: "Page ".(count($numbers)+1). Or, separate variable as you have done.
0

Thanks to datacompboy I finally came to this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.