dongluan7821
dongluan7821
2014-04-10 21:08

如何从foreach循环输出中分配PHP变量?

已采纳

I have a foreach loop which prints out the usernames of all entries in a database table like so:

foreach($results as $result){

echo $result->username;
echo '<br>';

}

As more and more users are added to the table, the list will grow. I would like to take the complete list and assign each entry to a separate PHP variable for use later on the PHP script. What is the best way to do this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

6条回答

  • donglu5728 donglu5728 7年前

    You don't want individual variables, try an array:

    foreach($results as $result){
        $names[] = $result->username;
    }
    
    点赞 评论 复制链接分享
  • dqb78642 dqb78642 7年前

    foreach loops are soooo out of fashion :p

    $names = array_map(function($r) {return $r->username;},$results);
    
    点赞 评论 复制链接分享
  • dpfwhb7470 dpfwhb7470 7年前

    Based on your comments I am trying to apply each username as a javascript variable, all you need seems to be something like:

    <script type="text/javascript">
      var usernames = <?php echo json_encode($results); ?>;
    </script>
    

    Of course if you only need one element from the $results array, you should first generate a reduced list using one of the other answers; if you use the whole $results array, all information in there will be sent to the browser / visible to the visitor.

    点赞 评论 复制链接分享
  • doubleyou1001 doubleyou1001 7年前

    Put them in an array:

    $names = array();
    foreach ($results as $result) {
        $names[] = $result->username;
    }
    
    点赞 评论 复制链接分享
  • doubei2340 doubei2340 5年前

    I don't know why you want too.... but you could do ...

    foreach($results as $result)
    {
        $$result->username = $result;
     }
    

    That answers your question. But why anyone would do that is beyond me

    点赞 评论 复制链接分享
  • dp19001 dp19001 5年前

    I use below code

    <?php
    
    $string = 'a|b|c|d|e|f';
    
    $tags = explode('|' , $string);
    
    
    foreach($tags as $i =>$key) {
    $i >0;
         $a[$i]=$key .'</br>';
    
    }
    
    echo $a[3];
    

    good luck

    点赞 评论 复制链接分享

相关推荐