How to store values from foreach loop into an array?
Need to store values from foreach loop into an array, need help doing that.
The code below does not work, only stores the last value, tried $items .= ...,
but that is 开发者_JAVA百科not doing the trick either, any help will be appreciated.
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
Declare the $items
array outside the loop and use $items[]
to add items to the array:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);
Use
$items[] = $username;
Try
$items = array_values ( $group_membership );
<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>
You can try to do my answer,
you wrote this:
<?php
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
?>
And in your case I would do this:
<?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;
} ?>
As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)
<?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
is faster, but the last example is only a result of an observation. :)
This is how you do it:
foreach($orders as $item){
$transactionIds[] = $item->generated_order_id;
}
dump($transactionIds);
This is assuming $orders collection has a field called 'generated_order_id'.
$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
Just try the above in your code .
Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>
精彩评论