简体   繁体   English

foreach 循环中的两个 arrays

[英]Two arrays in foreach loop

I want to generate a selectbox using 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?有什么建议么?

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 $names array...或者,让代码成为$names数组的键会容易得多......

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

foreach operates 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 foreach that 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.或者如其他答案中所见,您可以改为对关联数组进行硬编码。

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

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

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()来获得与之前完全相同的数组。

array_map seems 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 null values to fill in the gap.如果一个数组比另一个短,则回调接收null值以填补空白。

  • You can use more than 2 arrays to iterate through.您可以使用 2 个以上的数组进行迭代。

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

Your code like this is incorrect as foreach only for single array:您这样的代码不正确,因为 foreach 仅适用于单个数组:

<?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>';
            }
?>

Alternative, Change to this:替代方案,更改为:

<?php
        $codes = array('tn','us','fr');
        $names = array('Tunisia','United States','France');
        $count = 0;

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

?>

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

You can use array_merge to combine two arrays and then iterate over them.您可以使用 array_merge 组合两个数组,然后遍历它们。

$array1 = array("foo" => "bar");
$array2 = array("hello" => "world");
$both_arrays = array_merge((array)$array1, (array)$array2);
print_r($both_arrays);

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>';
?>

Walk it out...出去走走...

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

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

demo演示

<?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>';

?>

foreach only works with a single array. foreach 仅适用于单个数组。 To step through multiple arrays, it's better to use the each() function in a while loop:要遍历多个数组,最好在 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. each() 返回有关数组当前键和值的信息,并将内部指针加一,如果已到达数组末尾,则返回 false。 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.当两个数组之一完成时,循环终止。

Instead of foreach loop, try this (only when your arrays have same length).而不是 foreach 循环,试试这个(只有当你的数组具有相同的长度时)。

$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)  
{  
  for($i=0; $i<$number; $i++)//loop thru each arrays
  {
    $codes =$_POST['codes'][$i];
    $names =$_POST['names'][$i];
    //ur code in here
  }
}

array_combine()在组合来自多个表单输入的$_POST多个值以尝试更新购物车中的产品数量时对我来说非常array_combine()

I think that you can do something like:我认为您可以执行以下操作:

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

$names = array('Tunisia','United States','France'); $names = array('突尼斯','美国','法国');

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

It should also work for associative arrays.它也应该适用于关联数组。

I think the simplest way is just to use the for loop this way:我认为最简单的方法就是这样使用 for 循环:

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

for($i = 0; $i < sizeof($codes); $i++){
    echo '<option value="' . $codes[$i] . '">' . $names[$i] . '</option>';
}
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....现在您可以对每个数组使用 $a....

$doors[$a]
$windows[$a]
....
}

I solved a problem like yours by this way:我通过这种方式解决了像你这样的问题:

foreach(array_keys($idarr) as $i) {
 echo "Student ID: ".$idarr[$i]."<br />";
 echo "Present: ".$presentarr[$i]."<br />";
 echo "Reason: ".$reasonarr[$i]."<br />";
 echo "Mark: ".$markarr[$i]."<br />";
}

You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty您应该尝试将 2 个数组放入 singlr foreach 循环假设我有 2 个数组 1.$item_nm 2.$item_qty

 `<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td>  <td>item_qty</td>    </tr>

  @foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr> 
        <td> $i++  </td>
        <td>  $item_nm  </td>
        <td> $item_qty  </td>
   </tr></table>

@endforeach `

Few arrays can also be iterated like this:很少有数组也可以像这样迭代:

foreach($array1 as $key=>$val){ // Loop though one array
    $val2 = $array2[$key]; // Get the values from the other arrays
    $val3 = $array3[$key];
    $result[] = array( //Save result in third array
      'id' => $val,
      'quant' => $val2,
      'name' => $val3,
    );
  }

This will only work if the both array have same count.I try in laravel, for inserting both array in mysql db这仅在两个数组具有相同计数时才有效。我尝试在 Laravel 中将两个数组插入 mysql db

$answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"}; $answer = {"0":"0","1":"1","2":"0","3":"0","4":"1"};
$reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"}; $reason_id = {"0":"17","1":"19","2":"15","3":"19","4":"18"};

        $k= (array)json_decode($answer);
        $x =(array)json_decode($reason_id);
        $number = COUNT(json_decode($reason_id, true));
        if($number > 0)  
        {  
        for($i=0; $i<$number; $i++)
        {
            $val = new ModelName();
            $val->reason_id  = $x[$i];
            $val->answer  =$k[$i];
            $val->save();
        }
        }

En laravel Livewire恩 laravel Livewire

return view('you_name_view', compact('data','data2'));

@foreach ($data as $index => $data )

      <li>
          <span>{{$data}}</span>
          <span>{{$data2[$index]}}</span>
      </li>

@endforeach

it works for me这个对我有用

$counter = 0;
foreach($codes as $code)
{
$codes_array[$counter]=$code;
$counter++;
}
$counter = 0;
foreach($names as $name)
{
echo $codes_array[$counter]."and".$name;
$counter++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM