php foreach 循环中的两个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4480803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:09:19  来源:igfitidea点击:

Two arrays in foreach loop

phparraysforeach

提问by medk

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

我想selectbox使用两个数组生成一个,一个包含国家代码,另一个包含国家名称。

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?

这种方法对我不起作用。有什么建议?

回答by alex

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 $namesarray...

或者,使代码成为$names数组的键会容易得多......

$names = array(
   'tn' => 'Tunisia',
   'us' => 'United States',
   ...
);

回答by BoltClock

foreachoperates on only one array at a time.

foreach一次只对一个数组进行操作。

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

您的数组的结构方式,您可以将array_combine()它们转换为键值对数组,然后foreach是单个数组:

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.

或者如其他答案中所见,您可以改为对关联数组进行硬编码。

回答by Ignacio Vazquez-Abrams

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

用于array_combine()将数组融合在一起并迭代结果。

$countries = array_combine($codes, $names);

回答by Jacob Relkin

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.

我相信使用关联数组是最明智的方法,而不是使用,array_combine()因为一旦有了关联数组,您就可以简单地使用array_keys()array_values()获得与之前完全相同的数组。

回答by ankabot

array_mapseems good for this too

array_map似乎也适用于此

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

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

Other benefits are:

其他好处是:

  • If one array is shorter than the other, the callback receive nullvalues to fill in the gap.

  • You can use more than 2 arrays to iterate through.

  • 如果一个数组比另一个短,则回调接收null值以填补空白。

  • 您可以使用 2 个以上的数组进行迭代。

回答by PerceptorII

foreach only works with a single array. To step through multiple arrays, it's better to use the each() function in a while loop:

foreach 仅适用于单个数组。要遍历多个数组,最好在 while 循环中使用 each() 函数:

while(($code = each($codes)) && ($name = each($names))) {
    echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';
}

each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.

each() 返回有关数组当前键和值的信息,并将内部指针加一,如果已到达数组末尾,则返回 false。此代码不依赖于具有相同键或具有相同类型元素的两个数组。当两个数组之一完成时,循环终止。

回答by delAmux

This worked for me:

这对我有用:

$codes = array('tn', 'us', 'fr');
$names = array('Tunisia', 'United States', 'France');
foreach($codes as $key => $value) {
    echo "Code is: " . $codes[$key] . " - " . "and Name: " . $names[$key] . "<br>";
}

回答by Jakub

Why not just consolidate into a multi-dimensionalassociative 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');

回答by Funk Forty Niner

All fully tested

全部经过全面测试

3 ways to create a dynamic dropdown from an array.

从数组创建动态下拉列表的 3 种方法。

This will create a dropdown menu from an array and automatically assign its respective value.

这将从数组中创建一个下拉菜单并自动分配其各自的值。

Method #1 (Normal Array)

方法#1(法线数组)

<?php

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

echo '<select name="countries">';

foreach($names AS $let=>$word){
    echo '<option value="'.$let.'">'.$word.'</option>';
}
echo '</select>';

?>




Method #2 (Normal Array)

方法#2(法线数组)

<select name="countries">

<?php

$countries = array('tn'=> "Tunisia", "us"=>'United States',"fr"=>'France');
foreach($countries as $select=>$country_name){
echo '<option value="' . $select . '">' . $country_name . '</option>';
}
?>

</select>




Method #3 (Associative Array)

方法#3(关联数组)

<?php

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

echo '<select name="countries">';
echo '<option value="none">Select...</option>';
foreach ($my_array as $k => $v) {
    echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
?>

回答by oLinkWebDevelopment

Walk it out...

出去走走...

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

    array_walk($codes, function ($code,$key) use ($names) { 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    });
    
  • Before PHP 5.3

    array_walk($codes, function ($code,$key,$names){ 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    },$names);
    
  • or combine

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        echo '<option value="' . $code . '">' . $name . '</option>';
    })
    
  • in select

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        @$opts = '<option value="' . $code . '">' . $name . '</option>';
    })
    echo "<select>$opts</select>";
    
  • PHP 5.3+

    array_walk($codes, function ($code,$key) use ($names) { 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    });
    
  • PHP 5.3 之前

    array_walk($codes, function ($code,$key,$names){ 
        echo '<option value="' . $code . '">' . $names[$key] . '</option>';
    },$names);
    
  • 或结合

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        echo '<option value="' . $code . '">' . $name . '</option>';
    })
    
  • 在选择

    array_walk(array_combine($codes,$names), function ($name,$code){ 
        @$opts = '<option value="' . $code . '">' . $name . '</option>';
    })
    echo "<select>$opts</select>";
    

demo

演示