douwei2966 2014-05-21 05: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-21 06: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条)

报告相同问题?