检查第一个数组中的值是否在第二个数组中,然后创建第三个数组

时间:2013-03-06 03:26:43

标签: php arrays

1)向php发布复选框数组 2)比较POSTED数组,看看是否在主数组中。 3)如果是,则在新数组中添加“1” 4)如果它不在主数组中,则在新数组中添加“0”

这就是我所拥有的:

$posted_array = array("8", "9", "12", "17");

$master_array = array("8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20");

$db_input_array = array();

foreach($master_array as $key => $array_value) {
    foreach($posted_array as $posted_key => $posted_value) {
        if($array_value == $posted_value) {
            $db_input_array[$array_value] = "1"; 
        } else {
            $db_input_array[$array_value] = "0"; 
        }
    }
}

print_r($db_input_array);

期望的结果:

Array ( 
  [8] => 1 
  [9] => 1 
  [10] => 0 
  [11] => 0
  [12] => 1
  [13] => 0
  [14] => 0
  [15] => 0
  [16] => 0
  [17] => 1
  [18] => 0
  [19] => 0
  [20] => 0
) 

1 个答案:

答案 0 :(得分:3)

$db_input_array = array();
foreach($master_array as $m){
   if(in_array($m, $posted_array)){
      $db_input_array[$m]=1;
   }else{
      $db_input_array[$m]=0;
   }
}

http://codepad.org/NaW5zHe5