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:31
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]
....
}
查看更多
宁负流年不负卿
3楼-- · 2019-01-01 02:32

Use an associative array:

$code_names = array(
                    'tn' => 'Tunisia',
                    'us' => 'United States',
                    'fr' => 'France');

foreach($code_names as $code => $name) {
   //...
}

I believe that using an associative array is the most sensible approach as opposed to using array_combine() because once you have an associative array, you can simply use array_keys() or array_values() to get exactly the same array you had before.

查看更多
裙下三千臣
4楼-- · 2019-01-01 02:38

I think that you can do something like:

$codes = array('tn','us','fr');

$names = array('Tunisia','United States','France');

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

It should also work for associative arrays.

查看更多
初与友歌
5楼-- · 2019-01-01 02:39
<?php

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

echo '<table>';

foreach(array_keys($codes) as $i) {

     echo '<tr><td>';
     echo ($i + 1);
     echo '</td><td>';
     echo $codes[$i];
     echo '</td><td>';
     echo $names[$i];
     echo '</td></tr>';
}

echo '</table>';

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