仅在PHP循环期间值在特定组内时打印出某些内容

我在整个站点中使用了大量阵列,仅为了以下任务而更改其结构将很痛苦.我想用另一个数组制作几个选择框.我想要得到的输出是这样的:

/* Example Array:

  $allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals",
                      "Crocodilians","Turtles");

  $group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
*/

<select name='Amphibian'>
   <option value='0'>Frogs</option>
   <option value='1'>Toads</option>
</select>

<select name='Mammal'>
   <option value='2'>Bats</option>
   <option value='3'>Elephants</option>
   <option value='4'>Rats</option>
   <option value='5'>Seals</option>
</select>

<select name='Reptile'>
   <option value='6'>Crocodilians</option>
   <option value='7'>Turtles</option>
</select>

我无法弄清楚如何仅在$group每次迭代期间值在特定动物组内时打印出选项.我尝试过each()从$group获取下一个动物$endAnimal,然后如果$animal与$endAnimal相匹配,则中断内部循环,但是我还需要使循环开始以特定值打印选项.

<?php

 $allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");

$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");

foreach($group as $thisAnimal=>$category){

   $nextKey = (each($group));

   $endAnimal = $nextKey['key'];

   print "<select name='$category'>";

   foreach($allAnimals as $idx=>$animal){

      print "<option value='$idx'>$animal</option>";

      if($endAnimal === $animal){
          break;
      } 
   }

   print "</select>";

}

?>

解决方法:

请检查一下:

 <?php

 $allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");

$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");

$group_keys = array_keys($group); // get the keys of group array
$j = 0;
foreach($group_keys as $key => $group_k){
   print "<select name='$group[$group_k]'>";
   if(isset($group_keys[$key+1])){
    $new_value = $group_keys[$key+1];
   }else{
       $new_value = '';
   }
   if($new_value ==''){
      foreach($allAnimals as $key => $allAnm){
        print "<option value='$j'>$allAnm</option>";
        unset($allAnimals[$key]);
        $j ++;
      }
   }else{

        $key_from = array_search($new_value,$allAnimals);

       for($i = 0; $i<$key_from; $i++){
            print "<option value='$j'>$allAnimals[$i]</option>";
            unset($allAnimals[$i]);
            $j ++;

       }
   }

   $allAnimals = array_values($allAnimals);
   print "</select>";
}

输出:-https://eval.in/379462(eval.in)

本地端:-(为了更好地显示):-http://prntscr.com/7fmtbi

上一篇:如何在php文本框中遍历多行文本?


下一篇:每天来自细菌计数的php输出循环