从foreach类函数返回单个数组

时间:2014-05-21 05:56:43

标签: php arrays foreach

我正在使用foreach对数组字符串开发PHP类函数。它用于查询数据库,它应该在调用时返回一个新数组。

代码如下所示:

public function myForeach() {

   $arrayOne = $getData;

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

}

我很确定我在这里遗漏了一些东西。我希望输出是来自$ query的新数组。

目前,它返回一个数组:

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

单个字符串数组,而不是来自foreach的每个值。

我想要归还:

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

2 个答案:

答案 0 :(得分:2)

您在$query内返回foreach参数,然后您有一个else不适合任何地方(else需要if成为else for)。您还需要append数组的值:

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 :(得分:0)

更改您的代码,

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

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

注意:否if()是否可见?