PHP array in for loop doesn't add all values

i made this script:

$alleTijden = array("ma_v" => $_POST['maandag_van'],
                    "ma_t" => $_POST['maandag_tot'],
                    "di_v" => $_POST['dinsdag_van'],
                    "di_t" => $_POST['dinsdag_tot'],
                    "wo_v" => $_POST['woensdag_van'],
                    "wo_t" => $_POST['woensdag_tot'],
                    "do_v" => $_POST['donderdag_van'],
                    "do_t" => $_POST['donderdag_tot'],
                    "vr_v" => $_POST['vrijdag_van'],
                    "vr_t" => $_POST['vrijdag_tot'],
                    "za_v" => $_POST['zaterdag_van'],
                    "za_t" => $_POST['zaterdag_tot'],
                    "zo_v" => $_POST['zondag_van'],
                    "zo_t" => $_POST['zondag_tot']
);



foreach($alleTijden as $label => $tijden)   {
    $tijd = explode(":", $tijden);
    if(count($tijd[0]) != 0 && count($tijd[1]) != 0)    {
        $uur = $tijd[0];
        $minuten = $tijd[1];

        $rondeTijden = round_hour($uur, $minuten);
        $nieuweTijden = array($label=>$rondeTijden);  

    }
}

foreach($nieuweTijden as $label => $tijden) {
    echo $label.':'.$tijden.'<br>';
}

But the new Array (nieuweTijden) only add the last value in the loop. It needs to add all the values like the forst array on top (alleTijden).

What is it that i do wrong?


A note: naming your variables in your local language is considered bad tone. Maybe it's easier for you to write your variable names in Dutch (or whatever language that is), but I, same as most of other people here, see it as just random characters, making your code unreadable.

Now, to the point. As the docs suggest, to add a value to an existing array, you must use [] .

Your code: $nieuweTijden = array($label=>$rondeTijden); Right code: $nieuweTijden[] = array($label=>$rondeTijden);

Also, I'd suggest you define your array prior to adding values to it:

$nieuweTijden = [];

foreach($alleTijden as $label => $tijden)
{
    $tijd = explode(":", $tijden);

    if(count($tijd[0]) != 0 && count($tijd[1]) != 0)
    {
        // ...
        $nieuweTijden[] = array($label=>$rondeTijden);  
    }
}
链接地址: http://www.djcxy.com/p/59420.html

上一篇: <? 或<?php

下一篇: for循环中的PHP数组不会添加所有值