How to store values from foreach loop into an array?

前端 未结 8 751
我在风中等你
我在风中等你 2020-11-29 16:16

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 .= ...,

相关标签:
8条回答
  • 2020-11-29 16:21

    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);
    
    0 讨论(0)
  • 2020-11-29 16:22

    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. :)

    0 讨论(0)
  • 2020-11-29 16:31

    Use

    $items[] = $username;
    
    0 讨论(0)
  • 2020-11-29 16:31

    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);
    ?>
    
    0 讨论(0)
  • 2020-11-29 16:32

    Try

    $items = array_values ( $group_membership );
    
    0 讨论(0)
  • 2020-11-29 16:33

    Just to save you too much typos:

    foreach($group_membership as $username){
            $username->items = array(additional array to add);
        }
        print_r($group_membership);
    
    0 讨论(0)
提交回复
热议问题