Search code examples
phpmysqlarraysforeachbootstrap-duallistbox

Double foreach with if condition PHP


I need help because I have a problem of execution of my code. In my database I store a multiple select like an array with this format : ["5","6","7","8"] I use json_encode to store my array.

I have a form with select multiple (https://www.virtuosoft.eu/code/bootstrap-duallistbox).

This input is fill with datas of an table. So this is the list on the left who is filled.

I would like to fill the list on the right with my datas stored in database. To do this I have to put selected to each option corresponding. But I have no idea to do this ... I think I use double foreach with an if condition but....

Some code to explain this:

Table with all options saved : Table name : weddings
Fields : id, title

Table with selected options saved

Table name : steps
Fields : id, participants => this field has the number of weddings.id like ["5","6","7","8"]

To fill my select list, I do this

<select multiple="multiple" id="participants" class="form-control" name="participants[]">
    @foreach ($weddings as $wedding)
      <option value="{{ $wedding->id }}" >{{ $wedding->title }}  </option>
    @endforeach
</select>

To retrieve data from steps I do this

foreach(json_decode($step->participants) as $k => $v){
   echo '<option value="'.$v.'" selected>'.$v.'</option>';
}

Because I need to put 'selected' on an option, this one go to the right list.

How can I combine the 2 foreach to "selected" the value store in my steps table with weddings table ?

I hope you understand me.

Thank you very much.

PS : I use Laravel


Solution

  • Try this, and most importantly understand it !

    // select all participants
    // for example lets say you got this from your database 
    $data = '["5","7","9","2"]';
    // now decode it 
    $data = json_decode($data);
    
    $weddings = [];
    // convert values to integers 
    foreach($data as $key => $value) 
    { 
       $weddings[$key] = (Int) $value; 
    }
    
    // create select input 
    $input = '<select>';
    
    foreach($weddings as $id) 
    {
        // lets say you want wedding id 5 to be selected
        // all you have to do is add an If statement and that's it !
        if($id === 5) {
             // this is wedding id 5 ! 
             $input .= '<option value="'.$id.'" selected>'.$id.'</option>';
        } else if ($id === 7) {
              // do something with wedding id 7 ? 
             $input .= '<option value="'.$id.'" class="number7">'.$id.'</option>';
        } else {
             $input .= '<option value="'.$id.'">'.$id.'</option>';
        }
    } 
    
    // close select input tag 
    $input .= '</select>';
    
    echo $input;