如何在foreach循环中添加多维数组的新索引?

时间:2010-12-17 11:09:20

标签: php sql multidimensional-array foreach

再次发生地狱,我想知道如何在foreach循环中添加数据到新的数组索引?

我有的代码是,

// Connect to the database to gather all data pertaiing to the link in question
$assoResult = mysql_query("SELECT * FROM associate_users");
while ($assoRow = mysql_fetch_field($assoResult)) {
    $resultArray[] = $assoRow->name;
}

// Connect to the database to gather all data pertaiing to the link in question
$assoResult2 = mysql_query("SELECT * FROM associate_users WHERE id='$getID'");
while ($assoRow2 = mysql_fetch_object($assoResult2)) {

    foreach ($resultArray as $row) { 
        $array = array(array( 1 => $assoRow2->$row, 2 => $row, ),);
        echo "<br />"; print_r($array);
    }               
}

以下是来自“echo”br /&gt;“; print_r($ array);”的输出数据。线。

=============================================== ==================

Array ( [0] => Array ( [1] => 1 [2] => id ) )
Array ( [0] => Array ( [1] => Bob[2] => contactName ) )
Array ( [0] => Array ( [1] => Bob's Tyres [2] => company ) )
Array ( [0] => Array ( [1] => XXXXXXXXXXXXXX [2] => address1 ) )
Array ( [0] => Array ( [1] => XXXXXXXXXXXXXX [2] => address2 ) )
Array ( [0] => Array ( [1] => XXXXXXXXX [2] => address3 ) )
Array ( [0] => Array ( [1] => XXXXXX [2] => postcode ) )

正如你所看到的那样,数组正在被重新创建,我需要的是上面的数据在每个循环上递增第一维索引键,所以它看起来像......

=============================================== ==================

Array ( [0] => Array ( [1] => 1 [2] => id ) )
Array ( [1] => Array ( [1] => Bob[2] => contactName ) )
Array ( [2] => Array ( [1] => Bob's Tyres [2] => company ) )
Array ( [3] => Array ( [1] => XXXXXXXXXXXXXX [2] => address1 ) )
Array ( [4] => Array ( [1] => XXXXXXXXXXXXXX [2] => address2 ) )
Array ( [5] => Array ( [1] => XXXXXXXXX [2] => address3 ) )
Array ( [6] => Array ( [1] => XXXXXX [2] => postcode ) )

提前谢谢你,我已经完成了这项工作和绝望的所有选择。

3 个答案:

答案 0 :(得分:2)

将指定部分代码的值更改为

    $count=0; 
    foreach ($resultArray as $row) { 
            $array[$count][1] = $assoRow2->$row
            $array[$count][2]=$row;
            $count++;
            echo "<br />"; print_r($array);
        }   

答案 1 :(得分:1)

此代码可以为您提供所要求的输出,而不会低效地使用两个查询:

// Connect to the database to gather all data pertaining to the link in question
$result = mysql_query("SELECT * FROM associate_users WHERE id=" . (int)$getID);

$resultArray = array();
$resultCount = 0;
$row = mysql_fetch_assoc($result);

$count = 0;
foreach ($row as $key => $value) {
    $temp = array();
    $temp[$count] = array(1 => $value, 2 => $key);
    $count++;

    echo "<br />"; print_r($temp);
}

为什么你要这样,我不知道。

答案 2 :(得分:0)

    //extra code.declaring array
$array = array();
while ($assoRow2 = mysql_fetch_object($assoResult2)) {
    foreach ($resultArray as $row) { 
// 1st parameter is the array name, here array name is array .give gd name according to use
       array_push($array,array( 1 => $assoRow2->$row, 2 => $row, ));
        echo "<br />"; print_r($array);
    }               
}