本文介绍了PHP将Arrray1与Array2进行比较并找出差异.然后用零填充Array1的缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:绘制复选框,并将query1的ID分配给elementId,并从query2分配给复选框的值.但是问题是查询2与array1相比并不总是返回完整的9个值.而且我想在比较array1值后用零替换查询2中的缺失值.

Issue: Draw checkboxes and assign ID from query1 to elementId and values assigned to checkbox from query2. But the issue is query 2 not always returns full 9 values as compared to array1. And I want to replace missing values in query 2 with zero's after comparing the array1 values.

我的方法:

获取两个查询的结果集和

Get result set of two queries and

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.

推荐答案

尝试一下,例如:

$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
)

这篇关于PHP将Arrray1与Array2进行比较并找出差异.然后用零填充Array1的缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:52