如何在PHP循环中的数组内部循环 [英] 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)
)
}
)
}
)
]);
推荐答案
循环需要在外部才能创建最终数组.不要在数组内添加循环.
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);
注意: -您可以在insertOne()
之前打印数组,以检查是否获得了正确格式的数组或需要更多操作的数组.谢谢
Note:- you can print your array before insertOne()
to check that you are getting array of correct format or some more manipulation needed.Thanks
这篇关于如何在PHP循环中的数组内部循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!