2015-06-26 55 views
0

問題:繪製複選框並將query1中的ID分配給elementId,並將值分配給query2中的複選框。但問題是查詢2並不總是返回完整的9個值與array1相比。我想在比較array1值後用0替換查詢2中的缺失值。PHP比較Arrray1與Array2並找出差異。然後用零填充Array1的缺失值

我的方法:

兩個查詢獲取結果集和

query 1 resultset = $tresult; 
query 1 resultset = $assignedTiles; 


$a1 = array(); 
     while ($row = mysql_fetch_row($tresult)){ 
      $a1[] = $row; 
     } 

    $a2 = array(); 
     if (mysql_num_rows($assignedTiles)==0){ 
      //echo " inside if row null"; 
    $a2 = array ('0' => array ('0'),'1' => array ('0'),'2' => array 
     ('0'),'3' => array ('0'),'4' => array ('0'),'5' => array ('0'), 
     '6' => array ('0'),'7' => array ('0'),'8' => array ('0'));  
     }else{ 
      while($row = mysql_fetch_row($assignedTiles)){ 
       $a2[] = $row; 
      } 
     }    


    foreach($a1 as $aV){ 
     $aTmp1[] = $aV['0']; //setting array key 
    } 
    foreach($a2 as $aV){ 
     $aTmp2[] = $aV['0']; 
    } 

    $resultArr = array_diff($aTmp1,$aTmp2); 
    // getting the difference in both arrays 

    if($resultArr !=NULL){ 
     foreach($resultArr as $v){ 
      $v = str_replace($resultArr, "0", $aTmp1); 
     } 
    }else { echo "did not match"; } 


    $countVal = count($v); 
    $i=0; 
    $i<$countVal; 
    $i++; 

    foreach ($v as $tileId => $value){ 

echo "<td align=center > 
<input type='checkbox' id='checkBox$tileId ' value='$value' > 
</td>"; 
    } 

I'm pretty sure there is a better way to do this. Any ideas or suggestion 
would be really appreciated. 
+1

你使用一個關係數據庫。你爲什麼要在php中使用十字路口代碼,當你可以讓mysql輕鬆地爲你做這件事時? RDBMes是爲這種事情設計的。 –

+0

SELECT ** IFNULL **(searchwords,'null to string')as searchwords FROM'table_article'; @Marc B是rgiht。 – PHPJungle

+0

我明白你的觀點,但這是我能想出來的。正如你所說,有100種方法可以解決上述問題。 – edrupler

回答

0

試試這個,例如:

$a1 = [ 1 => 'one', 2 => 'two', 3 => 'three',5=>'fayve', 6=>'six']; 
$a2 = [ 2 => 'two', 5=>'five']; 

print_r(array_diff($a1, $a2)); 
$keys = array_keys($a1); 
foreach ($keys as $k) 
{ 
    if (!isset($a2[$k])) $a2[$k] = '0'; 
} 
print_r($a2); 

輸出:

Array 
(
    [1] => one 
    [3] => three 
    [5] => fayve 
    [6] => six 
) 
Array 
(
    [2] => two 
    [5] => five 
    [1] => 0 
    [3] => 0 
    [6] => 0 
) 
+0

真棒,這正是我正在尋找。感謝您抽出時間回答我的問題。 – edrupler