尝试使用PHP匹配两个数组时获取错误

时间:2016-11-15 05:45:40

标签: php arrays

我在使用PHP比较两个数组时遇到以下错误。

错误:

  

注意:第7行/opt/lampp/htdocs/test/search.php中的未定义偏移量 1

     

注意:第15行/opt/lampp/htdocs/test/search.php中未定义的偏移量: 1   
删除值

     

注意:第7行/opt/lampp/htdocs/test/search.php中的未定义偏移量 2

     

注意:第15行的/opt/lampp/htdocs/test/search.php中的未定义偏移量: 2   
删除值

我正在解释下面的代码。

$maindata=array(array('id'=>3),array('id'=>7),array('id'=>9));
 $childata=array(array('id'=>3),array('id'=>45));
for($i=0;$i<count($maindata);$i++){
      //print_r($childata);
       if(count($childata) > 0){
           if(in_array($childata[$i],$maindata)){
               echo "get the value \n".$maindata[$i]['id'];
               echo "insert the value \n".$maindata[$i]['id'];
               unset($childata[$i]);
               if(count($childata) > 0){
                   $childata=array_values($childata);
               }
           }else{
               echo "delete the value \n".$childata[$i]['id'];
               unset($childata[$i]);
               if(count($childata) > 0){
                   $childata=array_values($childata);
               }
           }
       }else{
           echo "get the value \n".$maindata[$i]['id'];
           echo "insert the value \n".$maindata[$i]['id'];
       }
    }

请帮我解决此错误。

1 个答案:

答案 0 :(得分:0)

  

有些不清楚为什么你在循环中的ifelse子句中做同样的事情。然而;下面是一个片段,可能会让您对如何重新审视您的方法有所了解。 Quick-Test Here

<?php

    $mainData   = array( array('id'=>3), array('id'=>7), array('id'=>9) );
    $childData  = array( array('id'=>3), array('id'=>45) );

    foreach($mainData as $iKey=>$subArray){
        echo "get the value \n"     . $mainData[$iKey]['id']  . "<br />";
        echo "insert the value \n"  . $mainData[$iKey]['id']  . "<br />";
        // CHECK TO SEE THAT THE ARRAY $childData IS NOT EMPTY
        if(!empty($childData)){
            // THEN LOOP THROUGH THE $childData ARRAY
            // AND IF YOU SIMILAR ELEMENT IS FOUND TO  EXIST IN $mainData
            // DELETE (UNSET) ITS EQUIVALENT IN THE $childData
            foreach($childData as $iKey2=>$subArray2){
                if(in_array($subArray2, $mainData)){
                    unset($childData[$iKey2]);
                }else{
                    // YOU ARE DOING EXACTLY THE SAME THING YOU DID IN THE IF CLAUSE
                    // HERE AGAIN IN THE ELSE CLAUSE: IS THAT WHAT YOU REALLY WANT?
                    // THAT IS YOU ARE REPEATING: "unset($childData[$iKey2]);" ???
                    echo "delete the value \n"  . $childData[$iKey2]['id'] . "<br />";
                    unset($childData[$iKey2]);

                    // MOST LIKELY; YOU DON'T NEED THIS ELSE CLAUSE AT ALL
                    // unset($childData[$iKey2]);
                }
            }
            // GET THE ARRAY VALUES IF THE $childData is NOT EMPTY
            $childData  = (!empty($childData))? array_values($childData):$childData;
        }
    }