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条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题