我如何获得所需的输出?我想检查array1“entry_id”是否与array2“entry_id”
不同我该怎么做?我尝试使用array_diff_key ..但它没有用
数组1
Array ( [0] => Array ( [entry_id] => 53242 [site_id] => 2 [channel_id] => 2 [author_id] => 5 [1] => Array ( [entry_id] => 76435 [site_id] => 8 [channel_id] => 8 [author_id] => 9
ARRAY2
Array ( [0] => Array ( [entry_id] => 89764 [site_id] => 1 [channel_id] => 1 [author_id] => 5 [1] => Array ( [entry_id] => 53242[site_id] => 7 [channel_id] => 9 [author_id] => 1
我想将array1和array2相互比较并获得所需的输出:
期望的输出:
Array ( [0] => Array ( [entry_id] => 76434 [site_id] => 8 [channel_id] => 8 [author_id] => 9 [1] => Array ( [entry_id] => 76435 [site_id] => 8 [channel_id] => 8 [author_id] => 9
答案 0 :(得分:0)
对于小尺寸的输入数组,基本上可以使用两个for循环来完成它。
示例代码(未经测试!):
// $array1 and $array2 are the inputs
// $array3 is output
$array3=array();
// Keep track of what we have already found
$buff=array();
foreach($array1 as $a1){
foreach($array2 as $a2){
// Check for matching ids and is not already used
if($a1['entry_id']==$a2['entry_id'] and !isset($buff[$a1['entry_id']])){
$array3[]=$a1;
$buff[$a1['entry_id']]=1;
}
}
}
print_r($array3); // Debug
编辑: OP想要相反,所以......
示例代码(已测试!):
// 2 pass filter
// $array1 and $array2 are the inputs
$array1=array(
array('entry_id'=>1,'t'=>"a1"),
array('entry_id'=>2,'t'=>"b1"),
array('entry_id'=>3,'t'=>"c1"),
);
$array2=array(
array('entry_id'=>1,'t'=>"a2"),
array('entry_id'=>2,'t'=>"b2"),
array('entry_id'=>4,'t'=>"d2"),
);
// $array3 is output
$array3=array();
// Keep track of what we have already found
$buff=array();
foreach($array1 as $a1) $buff[$a1['entry_id']]=array(1,$a1);
foreach($array2 as $a2){
if(isset($buff[$a2['entry_id']])){
$buff[$a2['entry_id']]=array(2,$a2);
}else{
$buff[$a2['entry_id']]=array(1,$a2);
}
}
foreach($buff as $k=>$v) if($v[0]==1) $array3[]=$v[1];
print_r($array3); // Debug
答案 1 :(得分:0)
试试这个:
<?php
$arreglo1 = Array (
Array (
"entry_id" => 53242,
"site_id" => 2,
"channel_id" => 2,
"author_id" => 1
),
Array (
"entry_id" => 76435,
"site_id" => 8,
"channel_id" => 8,
"author_id" => 9,
)
);
$arreglo2 = Array (
Array (
"entry_id" => 89764,
"site_id" => 1,
"channel_id" => 1,
"author_id" => 5
),
Array (
"entry_id" => 53242,
"site_id" => 7,
"channel_id" => 9,
"author_id" => 1
)
);
$cnt = 0;
foreach($arreglo1 as $arr1) {
foreach($arreglo2 as $arr2){
if ($arr1["entry_id"] == $arr2["entry_id"]) {
$agregarlo = FALSE;
break;
}
else {
$agregarlo = TRUE;
}
}
if ($agregarlo) {
$resultado[$cnt] = $arr1;
}
$cnt++;
}
var_dump($resultado);
?>
给你这个:
array(1) { [1]=> array(4) { ["entry_id"]=> int(76435) ["site_id"]=> int(8) ["channel_id"]=> int(8) ["author_id"]=> int(9) } }