[英]How to store values from foreach loop into an array?
需要將 foreach 循環中的值存儲到數組中,需要幫助才能做到這一點。
下面的代碼不起作用,只存儲最后一個值,嘗試過$items .= ...,
但這也不起作用,任何幫助將不勝感激。
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
在循環外聲明$items
數組並使用$items[]
將項添加到數組中:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);
用
$items[] = $username;
<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>
嘗試
$items = array_values ( $group_membership );
你可以試着做我的回答,
你寫了這個:
<?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
更快,但最后一個例子只是觀察的結果。 :)
$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
只需在您的代碼中嘗試上述操作。
只是為了節省您太多的錯別字:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
這是你如何做到的:
foreach($orders as $item){
$transactionIds[] = $item->generated_order_id;
}
dump($transactionIds);
這是假設 $orders 集合有一個名為“generated_order_id”的字段。
這個問題看起來很老,但如果你通過它,你可以使用 PHP 內置函數 array_push() 使用下面的示例將數據推送到數組中。
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.