在PHP foreach循环中动态添加数组

时间:2012-11-07 15:46:10

标签: php arrays loops foreach

我正在尝试从数据库动态地向现有数组添加新数组,但我的循环只是添加了mysql_fetch_row的最后一行。我认为它实际上覆盖了相同的数组。

PHP代码

<?php
$con = require_once('./dbconnect.php');

global $con;
mysql_select_db("packages", $con);
$packages = mysql_query("SHOW TABLES FROM packages");

while($row = mysql_fetch_row($packages)){
    $node = array();

    foreach($row as $key2 => $value2){
        $node[$row[0]] = array("Item1" => "Other dynamic Info here");
    }
}

print_r($node);

mysql_close($con);
?>

输出如下:

Array
(
    [Pack1] => Array
        (
            [Item1] => Other dynamic Info here
        )

)

应输出:

Array
(
    [Pack1] => Array
        (
            [Item1] => Other dynamic Info here
        )

)
Array
(
    [Pack2] => Array
        (
            [Item2] => Other dynamic Info here
        )

)

我一直试图让这个foreach()循环工作大约一天......我做错了什么?

4 个答案:

答案 0 :(得分:1)

尝试将while循环外的$ node数组定义为:

$node = array(); ## <-- HERE

while ($row = mysql_fetch_row($packages))
{    
    foreach ($row as $key2 => $value2) 
    {
        $array      = array("Item1" => "Other dynamic Info here");
        $key        = $row[0];
        $node[$key] = $array;
    }
}

您还可以使用var_dump调试代码,以便在出现问题时更快地找到答案。

答案 1 :(得分:0)

应该是

foreach($row as $key2 => $value2){
    $node[$key2] = array("Item1" => "Other dynamic Info here");
}

答案 2 :(得分:0)

声明

$node = array();
在while循环之外。

如果节点数组的索引无关紧要,您可以使用“追加”符号

foreach($row as $key2 => $value2){
    node[] = array("Item1" => "Other dynamic Info here");
}

答案 3 :(得分:0)

您通过while循环在每个循环中覆盖数组,但仅在最后一个循环后输出一次数组。您的代码应如下所示(请注意print_r的位置):

<?php
$con = require_once('./dbconnect.php');

global $con;
mysql_select_db("packages", $con);
$packages = mysql_query("SHOW TABLES FROM packages");

while($row = mysql_fetch_row($packages)){
    $node = array();

    foreach($row as $key2 => $value2){
        $node[$row[0]] = array("Item1" => "Other dynamic Info here");
    }
    print_r($node);
}

mysql_close($con);
?>

这将通过while循环在每个循环中输出数组。