foreach 循环中的两个数组 [英] Two arrays in foreach loop
本文介绍了foreach 循环中的两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用两个数组生成一个 selectbox
,一个包含国家代码,另一个包含国家名称.
I want to generate a selectbox
using two arrays, one containing the country codes and another containing the country names.
这是一个例子:
<?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?
推荐答案
foreach( $codes as $code and $names as $name ) { }
这是无效的.
你可能想要这样的东西......
You probably want something like this...
foreach( $codes as $index => $code ) {
echo '<option value="' . $code . '">' . $names[$index] . '</option>';
}
或者,将代码作为 $names
数组的键会容易得多...
Alternatively, it'd be much easier to make the codes the key of your $names
array...
$names = array(
'tn' => 'Tunisia',
'us' => 'United States',
...
);
这篇关于foreach 循环中的两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文