Two arrays in foreach loop

后端 未结 22 1522
不思量自难忘°
不思量自难忘° 2020-11-22 04:48

I want to generate a selectbox using two arrays, one containing the country codes and another containing the country names.

This is an example:

相关标签:
22条回答
  • 2020-11-22 05:50
    if(isset($_POST['doors'])=== true){
    $doors = $_POST['doors'];
    }else{$doors = 0;}
    
    if(isset($_POST['windows'])=== true){
    $windows = $_POST['windows'];
    }else{$windows = 0;}
    
    foreach($doors as $a => $b){
    

    Now you can use $a for each array....

    $doors[$a]
    $windows[$a]
    ....
    }
    
    0 讨论(0)
  • 2020-11-22 05:51
    foreach( $codes as $code and $names as $name ) { }
    

    That is not valid.

    You probably want something like this...

    foreach( $codes as $index => $code ) {
       echo '<option value="' . $code . '">' . $names[$index] . '</option>';
    }
    

    Alternatively, it'd be much easier to make the codes the key of your $names array...

    $names = array(
       'tn' => 'Tunisia',
       'us' => 'United States',
       ...
    );
    
    0 讨论(0)
  • 2020-11-22 05:51

    You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty

     `<?php $i=1; ?>
    <table><tr><td>Sr.No</td> <td>item_nm</td>  <td>item_qty</td>    </tr>
    
      @foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
    <tr> 
            <td> $i++  </td>
            <td>  $item_nm  </td>
            <td> $item_qty  </td>
       </tr></table>
    
    @endforeach `
    
    0 讨论(0)
  • 2020-11-22 05:52

    foreach operates on only one array at a time.

    The way your array is structured, you can array_combine() them into an array of key-value pairs then foreach that single array:

    foreach (array_combine($codes, $names) as $code => $name) {
        echo '<option value="' . $code . '">' . $name . '</option>';
    }
    

    Or as seen in the other answers, you can hardcode an associative array instead.

    0 讨论(0)
提交回复
热议问题