foreach循环有两个数组

时间:2016-12-19 10:54:46

标签: php arrays

我想使用两个数组生成一个选择框,一个包含option-value和option-name,另一个包含选项的数据值

例如:

"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>

}

连连呢?感谢

6 个答案:

答案 0 :(得分:3)

它实际上使用一个array ($key+1)$array_1的键值,如果你从1开始数组键值而不是0,这是一个建议:

<?php

$arry_1  = array("1" => "orange", "2" => "banana", "3" => "apple");
$data_array  = array("first" , "second" , "third");

foreach ($data_array as $key => $value) {
  echo '<option value="'.($key+1).'" data-value="'.$value.'">orange</option>';
}
?>

答案 1 :(得分:3)

使用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>";
}

答案 2 :(得分:2)

通过执行以下操作,您可以更加简化:

<?php
foreach ($array as $index => $title)
{
    echo "<option data-value='" . $data[$index] . "'>$title</option>";
}
?>

答案 3 :(得分:1)

我认为您可以使用下面的一个关联数组来实现这一点 -

 //you can construct associative array like this
 $array = array("first"=>"orange","second"=>"banana","third"=>"apple");
 $count =1;
 foreach($array as $key=>$val)
 {
   echo '<option value='.$count.' data-value="'.$key.'"'.'>'.$val.'</option';
   $count++;  
 }

如果您想使用问题中给出的两个数组 -

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

for($i=1 ; $i<=count($arr['arra1']);$i++) 
{
  echo '<option value='.$i.'  data-value="'.$arr['data-array'][$i-1].'">'.$arr['arra1']["$i"].'</option>';
}

答案 4 :(得分:1)

这有助于获得所需的输出:

$arra1  = array("1" => "orange", "2" => "banana", "3" => "apple");
$data_array  = array("first" , "second" , "third");

echo "<select>";
foreach ($arra1 as $key => $value) {
  echo '<option value="'.($key).'" data-value="'.$data_array[$key-1].'">'.$value.'</option>';
}
echo "</select>";

答案 5 :(得分:1)

了解array_map。您可以为其提供任意数量的数组,并且并行地遍历它们:

$options = array_map(function ($key, $value, $datum) {
    return "<option value=\"$key\" data-value=\"$datum\">$value</option>";
}, array_keys($arry_1), $arry_1, $data_array);

这是working demo

请注意,为了传递密钥以及我使用array_keys函数的值。