简体   繁体   English

for循环中的PHP数组

[英]PHP Array within the for loop

Is there a way to create an array within the for loop. 有没有一种方法可以在for循环中创建数组。 There are several similar answers here, but none of them or the logic from these answers is applicable in the code below. 这里有几个类似的答案,但是它们中的任何一个或这些逻辑中的逻辑均不适用于以下代码。

for($j=1;$j<6;$j++) {
    $odg[$j] = "";
}
//the rest of the code which gives values to the array elements (outside the loop)

This is how array should look like before insert it into the sql query. 这是将数组插入sql查询之前的样子。

$odg_ids = array($odg[1],$odg[2],$odg[3],$odg[4],$odg[5]);
$odg_list = implode("','", $odg_ids);

This is the for loop that should generate an array. 这是应该生成数组的for循环。

for($i=1;$i<6;$i++) {
    $odg_ids[] = $odg[$i];
    $odg_list[] = implode("','", $odg_ids[$i]);
}

Something's missing? 缺少什么?

You need to do the implode after the loop. 您需要在循环进行implode Otherwise you keep appending to odg_list each time. 否则,您每次都会附加到odg_list

for ($i=1;$i<6;$i++) {
    $odg_ids[] = $odg[$i];
}
$odg_list = implode("','", $odg_ids[$i]);

I'm not sure where you get 6 from, but you could also use array_slice to get the 1st through 6th elements (you are omitting the 0th element). 我不确定从哪里获得6 ,但是您也可以使用array_slice获取第1到第6个元素(您省略了第0个元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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