Two arrays in foreach loop

后端 未结 22 1559
不思量自难忘°
不思量自难忘° 2020-11-22 04:48

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

This is an example:

相关标签:
22条回答
  • 2020-11-22 05:44

    You can use array_merge to combine two arrays and then iterate over them.

    $array1 = array("foo" => "bar");
    $array2 = array("hello" => "world");
    $both_arrays = array_merge((array)$array1, (array)$array2);
    print_r($both_arrays);
    
    0 讨论(0)
  • 2020-11-22 05:45

    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,
        );
      }
    
    0 讨论(0)
  • 2020-11-22 05:46

    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.

    0 讨论(0)
  • 2020-11-22 05:46

    I think the simplest way is just to use the for loop this way:

    $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>';
    }
    
    0 讨论(0)
  • 2020-11-22 05:46

    array_combine() worked great for me while combining $_POST multiple values from multiple form inputs in an attempt to update products quantities in a shopping cart.

    0 讨论(0)
  • 2020-11-22 05:47

    Instead of foreach loop, try this (only when your arrays have same length).

    $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
      }
    }
    
    0 讨论(0)
提交回复
热议问题