php foreach循环只输出最后一个数组键值

时间:2022-02-15 22:09:26

I have some code to generate 4 unique random numbers between 0-9: -

我有一些代码生成0-9之间的4个唯一随机数: -

//Globals
$arr = array();
$gridMax = 9;
$i = 0;


while ( count($arr) < 4 ) {
$x = mt_rand(0, $gridMax);
    if ( !in_array($x, $arr) ) {
        $arr[] = $x;

        }
}

print_r($arr);

I'm trying to create a grid and if the corresponding grid number is the same as one of the 4 unique values in my array then I want it to add some text to the $build variable. If not, do nothing: -

我正在尝试创建一个网格,如果相应的网格数与我的数组中的4个唯一值之一相同,那么我希望它在$ build变量中添加一些文本。如果没有,什么都不做: -

while ($i <= $gridMax) {
foreach ($arr as $value) {
    if ($value == $i) { 
        $build = "build";
    } else {
        $build = "";
    }

}

echo "<li class=\"map\">{$build}</li>";
$i++;
}

However, it only works for the final value in the last key (shown here): -

但是,它仅适用于最后一个键中的最终值(如下所示): -

http://www.kryptonite-dove.com/sandbox/mt_rand/

http://www.kryptonite-dove.com/sandbox/mt_rand/

Can anyone give me some pointers? I've been absent from coding for a number of months and my mind is a little foggy!

任何人都可以给我一些指示吗?我已经缺席了几个月的编码,我的思绪有点模糊!

2 个解决方案

#1


1  

while ($i <= $gridMax) 
{
    $build = '';
    if(in_array($i, $arr)) $build = 'build';

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}

#2


1  

What about this:

那这个呢:

while ($i <= $gridMax) 
{
    $build = '';

    foreach ($arr as $value) 
    {
        if ($value == $i) 
        { 
            $build .= "build";
        }   
        else        
        {
            $build .= "";
        }
    }

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}

#1


1  

while ($i <= $gridMax) 
{
    $build = '';
    if(in_array($i, $arr)) $build = 'build';

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}

#2


1  

What about this:

那这个呢:

while ($i <= $gridMax) 
{
    $build = '';

    foreach ($arr as $value) 
    {
        if ($value == $i) 
        { 
            $build .= "build";
        }   
        else        
        {
            $build .= "";
        }
    }

    echo "<li class=\"map\">{$build}</li>";
    $i++;
}