![](/img/trans.png)
[英]Two arrays are getting created when trying to fetch array values using a string match in php
[英]Getting error while trying to match two array using PHP
我在使用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'];
}
}
请帮我解决这个错误。
有些不清楚为什么你在你的循环中的
if
和else
子句中做同样的事情。 然而; 下面是一个片段,可能会让您对如何重新审视您的方法有所了解。 在这里快速测试 :
<?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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.