dongyue934001 2018-03-09 11:50
浏览 20
已采纳

如何使用PHP在数组内循环

How can I loop inside an array in PHP?

I'm working with mongodb and php and I'm trying to loop inside an array to repeat 50 times the same. Just getting in contact with mongodb. Code:

$whatever->insertOne(
    ['name' => 'whatever',
     'data' => array(
          for ($i = 0 ; $i < 50 ; $i++) {
              '1' => array(
                  'date' => $date,
                  'value' => mt_rand(0,200)
               ),
          }
    ]);

This is the loop that I'm trying to run, but clearly is not going to work.

for ($i = 0 ; $i < 50 ; $i++) {}

And yes, I know I would repeat the '1' 50 times, which it doesn't make sense, but I'm just giving a change to mongodb.

  • 写回答

1条回答 默认 最新

  • doutuan8887 2018-03-09 11:55
    关注

    First construct the object with an empty data, then fill it with your loop, then submit it to mongo

    $toSend = ['name' => 'whatever', 'data' => array()];
    
    for ($i = 0 ; $i < 50 ; $i++) {
         $toSend['data'][] = [
             '1' => [
                 'date' => $date,
                 'value' => mt_rand(0,200)
             ]
         ];
    }
    
    $whatever->insertOne($toSend);
    

    Anyway, let's pretend for a second that you didn't want the outer array inside data. That means you can't use the same key, so let's use $i for that.

    for ($i = 0 ; $i < 50 ; $i++) {
         $toSend['data']["$i"] = [
             'date' => $date,
             'value' => mt_rand(0,200)
         ];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改