简体   繁体   English

PHP:在循环内定义变量/数组

[英]PHP: Define variables / array within a loop

I've got this code 我有这个代码

$vote = array(
    $arrayName[0][firstsector],
    $termin[1][firstsector],
    $termin[2][firstsector],
    $termin[3][firstsector]
);

Now I want to create a loop for it. 现在,我想为其创建一个循环。 I tried this: 我尝试了这个:

$howMuchIneed = 5;

for ($x = 0; $x <= $howMuchIneed; $x++) {
    $vote = array(
        $arrayName[$x][firstsector]
    );
}

But the result doesn't look the same as the first code. 但是结果看起来与第一个代码不同。

Have you tried this ? 你尝试过这个吗?

for ($x = 0; $x <= $howMuchIneed; $x++) {
    array_push($vote, $arrayName[$x][firstsector]);
}

initializes Array 初始化数组

$vote = array();

If you want to learn more about array_push http://php.net/manual/en/function.array-push.php 如果您想了解更多有关array_push的信息,请访问 http://php.net/manual/en/function.array-push.php

Try this (in your for loop): 试试这个(在您的for循环中):

$vote[] = $arrayName[$x]['firstsector'];

... and don't forget to declare your array before your loop! ...并且不要忘记在循环之前声明数组!

$vote = array();

And in your first example you have 4 elements, condition in your for should be $x < 4 - arrays in PHP are zero-based. 在第一个示例中,您有4个元素, for条件应为$x < 4 -PHP中的数组基于零。

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

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