dtntjwkl83750 2016-09-16 14:34
浏览 25
已采纳

添加数组项,然后重新评估新数组

Have been scratching my head for a few hours on this, seems like a silly issue, but just can't find a solution.

Here's my sample code:

$continueLoop = true;
$colorsArray = array("red", "white", "blue");

while($continueLoop == true) {

$arrayCount = count($colorsArray);

for ($i=0; $i < $arrayCount; $i++) {
    echo "evaluating ".$colorsArray[$i]."<br>";
    if($colorsArray[$i] == "blue") {
        array_push($colorsArray, "YELLOW");
        break;
    }
}

if(count($colorsArray) == 4) {
    $continueLoop = false;
}

}

It outputs

red

white

blue

Basically I am adding a color "YELLOW" and then it should walk through the whole array again. But it's ignoring the newly added array item.

I know it does recognize the item, because the while loop will keep running until $colorsArray has 4 items (in the beginning it has only 3).

So why is it not Echo'ing "YELLOW"?

I've tried a few different solutions, just pushing the item using $array[], using foreach, array_values etc. etc.

Thank you

Update:

If i put

if(count($colorsArray) == 10) {

Still still won't print Yellow

  • 写回答

1条回答 默认 最新

  • dpw50696 2016-09-16 14:43
    关注

    Will probably clean this up in a moment but just quickly this should do the job;

    $colorsArray = array("red", "white", "blue");
    
    for ($i=0; $i < count($colorsArray); $i++) {
        echo "evaluating ".$colorsArray[$i]."<br>";
        if($colorsArray[$i] == "blue" && !in_array('YELLOW', $colorsArray)) {
            array_push($colorsArray, "YELLOW");
        }
    }
    
    print_r($colorsArray);
    

    Essentially you use count on each iteration, since the length of the array changes, it now has another element to loop through.

    Edit: If you want it to walk through the whole array again, just set $i = -1; after you push in a new element.

    Edit2: A little clean up.

    $colours = array('red', 'white', 'blue');
    
    for ($i = 0; $i < count($colours); ++$i) {
        echo 'Evaluating: ' . $colours[$i] . '<br/>';
    
        if ($colours[$i] === 'blue' && !in_array('Yellow', $colours)) {
            array_push($colours, 'Yellow');
            $i = -1;
        }
    }
    

    Output:

    Evaluating: red
    Evaluating: white
    Evaluating: blue
    Evaluating: red
    Evaluating: white
    Evaluating: blue
    Evaluating: Yellow
    
    • If you reset the loot to 0 rather than -1 then you skip the first loop iteration, i.e. you miss out red.
    • Not sure on your dataset / purpose for this but I imagine you would want 'Yellow' to be dynamic.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?