从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"}

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.
}

change your code,

$query = // query the value in the DB;
return $query;

To

$query[] = // query the value in the DB;

Note: no if() is visible for else?