This question already has answers here:
How can I loop through two arrays at once? [duplicate]

(2个答案)


3年前关闭。





我想使用两个数组生成一个选择框,一个包含选项值和选项名称,另一个包含选项的数据值

例如:

"arra1"  => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array"  => array("first" , "second" , "third"),


结果必须是

foreach( ??? ) {

<option value=1 data-value="first">orange</option>
<option value=2 data-value="second">banana</option>
<option value=3 data-value="third">apple</option>

}


有什么建议吗?谢谢

最佳答案

使用PHP的array_values函数以相同的索引获取两个数组,然后执行foreach:

$data = [
    "arra1"  => array("1" => "orange", "2" => "banana", "3" => "apple"),
    "data-array"  => array("first" , "second" , "third")
];

$labels = array_values($data["arra1"]);
$values = array_values($data["data-array"]);

foreach($labels as $index => $value) {
    $optionValue = $index+1;
    echo "<option value={$optionValue} data-value='{$values[$index]}'>{$labels[$index]}</option>";
}

关于php - 具有两个数组的foreach循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41221032/

10-13 04:52