简体   繁体   中英

How to loop inside an array inside a loop in PHP

Basically, what I'm trying to do is loop inside a loop and in arrays. I have no idea how to do it (that's why I'm here) and I've been testing many things.

As it sounds very confused I write down the code how it would be, but clearly that's not correct.

This below is what I've tried.

$whatever->insertOne(
    ['name' => 'whatever',
    'data' => array(
        for ($i = 0 ; $i < 50 ; $i++) { // <-first loop
            'something' => array(
                for ($j = 0 ; $j < 50 ; $j++) { // <-second loop
                    'somevalue' => array(
                        'date' => $date,
                        'value' => mt_rand(0,200)
                    ) 
                }
            )
        }
    )

    ]);

Try this out:

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

Loop need to be outside to create final array. Don't add loop inside an array.

You probably need something like below:-

$data = ['name' => 'whatever'];

for ($i = 0 ; $i < 50 ; $i++) {
  for ($j = 0 ; $j < 50 ; $j++) {
    $data[$i]['something'][$j]=['somevalue' => array('date' => $date,'value' => mt_rand(0,200));
  }
}

$whatever->insertOne($data);

Note: - you can print your array before insertOne() to check that you are getting array of correct format or some more manipulation needed.Thanks

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