简体   繁体   中英

Foreach loop looping twice

So my problem is that it is looping twice and that is not the desired output that I wanted.So to start of I have a 3 checkbox with each value 1 till 3 which is sent to the database and is divided by a '@|@' sign.

Example of content for $rs_array['package'] for 3 checkboxes picked

1@|@2@|@3

Down here is the foreach loop of it

if(strpos($rs_array['package'], '@|@') == true){
$array = explode('@|@', $rs_array['package']);
foreach ($array as $myArray) {
    if ($myArray==1) {
        $myArray = "Starter";
    }
    elseif ($myArray==2) {
        $myArray = "Developing";
    }
    elseif ($myArray==3){
        $myArray = "Matured";
    }
    $my_Array[] =  $myArray;
}
//unset($my_Array);
$my_Arrays = implode(',', $my_Array);
}
else{

    $my_Arrays = $rs_array['package'];
    if($my_Arrays==1){
    $my_Arrays = "Starter";
    }
    elseif ($my_Arrays==2) {
        $my_Arrays = "Developing";
    }
    elseif ($my_Arrays==3) {
        $my_Arrays = "Matured";
    }
    else{
        $my_Arrays = "";
    }
}
echo $my_Arrays;

And down here is the output of the echo when I pick three of them

Starter,Developing,Matured,Starter,Developing,Starter,Developing,Matured

And here is when I pick two of them

Starter,Developing,Matured,Starter,Developing

I am still a rookie in this foreach field so do mind that I still can't figure a workaround or even why it display as such.Much help is appreciated

-------problem-----

Now I see the problem that is if I have only one row of $rs_array['package'] it works fine but the problem is if there is two or more. It just adds up on the second one and so on... and I need a way so that it identifies that each of those rows are different

You can just directly push them on your array:

if(strpos($rs_array['package'], '@|@') == true){
     $array = explode('@|@', $rs_array['package']);
         foreach ($array as $myArray) {
             if ($myArray==1) {
               $my_Array[] = "Starter";
             } elseif ($myArray==2) {
               $my_Array[] = "Developing";
             } elseif ($myArray==3){
               $my_Array[] = "Matured";
             }    
         }
         //unset($my_Array);
         $my_Arrays = implode(',', $my_Array);
}
echo $my_Arrays;

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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