如何将foreach循环中的值存储到数组中?

时间:2010-06-15 13:35:32

标签: php foreach

需要将foreach循环中的值存储到数组中,需要帮助。下面的代码不起作用,只存储最后一个值,尝试$ items。= ...,但这也不是诀窍,任何帮助都将受到赞赏。

<?php
foreach($group_membership as $i => $username) {
 $items = array($username);
}

print_r($items);
?>

8 个答案:

答案 0 :(得分:228)

在循环外声明$items数组并使用$items[]向数组添加项目:

$items = array();
foreach($group_membership as $username) {
 $items[] = $username;
}

print_r($items);

答案 1 :(得分:14)

使用

$items[] = $username;

答案 2 :(得分:7)

尝试

$items = array_values ( $group_membership );

答案 3 :(得分:3)

<?php 
$items = array();
$count = 0;
foreach($group_membership as $i => $username) { 
 $items[$count++] = $username; 
} 
print_r($items); 
?>

答案 4 :(得分:2)

你可以尝试回答我,

你写了这个:

<?php
foreach($group_membership as $i => $username) {
    $items = array($username);
}

print_r($items);
?>

在你的情况下,我会这样做:

<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
    $items[] = $username;
} ?>

正如您在问题中所示,您似乎需要一个特定组中的用户名数组:)在这种情况下,我更喜欢使用简单的while循环进行良好的SQL查询;)

<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
    $items[] = $username; 
} 
?>

while更快,但最后一个例子只是观察的结果。 :)

答案 5 :(得分:1)

$items=array(); 
$j=0; 

foreach($group_membership as $i => $username){ 
    $items[$j++]=$username; 
}

只需在代码中尝试以上操作。

答案 6 :(得分:0)

这个问题看起来很旧,但是如果你传递它,你可以使用PHP内置函数array_push()来使用下面的例子推送数组中的数据。

<?php
    $item = array();
    foreach($group_membership as $i => $username) {
        array_push($item, $username);
    }
    print_r($items);
?>

答案 7 :(得分:0)

只是为您节省了很多错字:

foreach($group_membership as $username){
        $username->items = array(additional array to add);
    }
    print_r($group_membership);
相关问题