获取嵌套数组中的父键

时间:2012-04-14 08:05:41

标签: php multidimensional-array nested

我正在构建一个从数据库中获取的“嵌套”数组;这是我的剧本:

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

我想获得以下数组(带有print_r()函数),但我完全不知道如何获取页码:

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
        )

)

我试过了:

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

但它没有导致预期的结果(在我看来,它应该得到“父”数组的当前键号并增加1)

请帮忙吗? 提前致谢

2 个答案:

答案 0 :(得分:2)

算一下你自己:

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

或者,在代码中使用count($numbers)+1

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

答案 1 :(得分:0)

感谢datacompboy,我终于来到了这个:

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