Two arrays in foreach loop

2019-01-01 01:56发布

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

This is an example:

<?php
    $codes = array('tn','us','fr');
    $names = array('Tunisia','United States','France');

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

This method didn't work for me. Any suggestions?

标签: php arrays
22条回答
残风、尘缘若梦
2楼-- · 2019-01-01 02:23

Use array_combine() to fuse the arrays together and iterate over the result.

$countries = array_combine($codes, $names);
查看更多
还给你的自由
3楼-- · 2019-01-01 02:24

Why not just consolidate into a multi-dimensional associative array? Seems like you are going about this wrong:

$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');

becomes:

$dropdown = array('tn' => 'Tunisia', 'us' => 'United States', 'fr' => 'France');
查看更多
笑指拈花
4楼-- · 2019-01-01 02:25

If it would be possible to do as you like, the foreach for 2 arrays would be programmed like that:

//foreach ($array1 as $key1 [,/and/~/'/-/whatever] $array2 as $key2)
    //equals:

    $array1 = array(); 
    $array2 = array();

    if (sizeof(array1) == sizeof(array2)){

    for ($i = 0; i < sizeof(array1) , i++){
    $key1 = $array1[$i]
    $key2 = $array2[$i]

    //the code

    }}

My solution isn't perfect but is okay for most purposes.

查看更多
怪性笑人.
5楼-- · 2019-01-01 02:26

array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.

查看更多
梦醉为红颜
6楼-- · 2019-01-01 02:26

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 `
查看更多
无色无味的生活
7楼-- · 2019-01-01 02:30

Your code like this is incorrect as foreach only for single array:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');

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

Alternative, Change to this:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');
        $count = 0;

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

?>
查看更多
登录 后发表回答