简体   繁体   中英

How to loop inside an array with 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.

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)
     ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM