douwei2966 2014-05-20 21:56
浏览 103
已采纳

从foreach类函数返回单个数组

I'm working on a PHP class function using foreach on array strings. It's used to query the DB and it should return a new array when called.

The code looks like this:

public function myForeach() {

   $arrayOne = $getData;

   foreach($arrayOne as $key=>$value){
      $query = // query the value in the DB;
   }
   return $query;
}else {
   return false;

}

I'm pretty sure I'm missing something here. What I want the output to be is a new array from the $query.

At the moment, it returns an array like :

array(1) { [0]=> string(14) "returnedstring" }

A single string array, rather than each value from the foreach.

I want to return this:

array(2) { [0]=> string(15) "returnedstring1" [1]=> string(15) "returnedstring2"}
  • 写回答

2条回答 默认 最新

  • duanluan8390 2014-05-20 22:01
    关注

    You return the $query parameter inside the foreach, then you have an else that dont fit in anywhere (else requires an if to be an else for). You will also need to append the value to the array:

    public function myForeach() {
      $arrayOne = $getData;
      $query = array(); // Create the $query array.
      foreach($arrayOne as $key=>$value){
        $query[] = // Append the query array with whatever value you have.
      }
      return $query; // Return the array when the for-each loop is done.
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部