$abc = array(
a1=>array(a=>1,b=>1,c=1,d=2),
a2=>array(a=>1,b=>2,c=2,d=2),
a3=>array(a=>3,b=>2,c=3,d=2)
)
现在我需要将上面的二维数组合并为一维数组。
一维数组需要包含a=1 and b=1 这个数组的所有信息 和 a=3 这个数组的所有信息,我想请问一下,这种整理,使用一个foreach 可以整理出来么。
------解决方案--------------------
$abc = array(
'a1' => array('a' => 1, 'b' => 1, 'c' => 1, 'd' => 2),
'a2' => array('a' => 1, 'b' => 2, 'c' => 2, 'd' => 2),
'a3' => array('a' => 3, 'b' => 2, 'c' => 3, 'd' => 2),
);
$filter = array(
array( 'a' => 1, 'b' => 1),
array( 'a' => 3),
);
$res = array();
foreach($abc as $item) {
foreach($filter as $f) {
if(array_intersect_assoc($f, $item) == $f)
$res = array_merge($res, array_values($item));
}
}
print_r($res);
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 3
[5] => 2
[6] => 3
[7] => 2
)
------解决方案--------------------
$abc = array(
'a1'=>array('a'=>'1','b'=>'1','c'=>'1','d'=>'2'),
'a2'=>array('a'=>'1','b'=>'2','c'=>'2','d'=>'2'),
'a3'=>array('a'=>'3','b'=>'2','c'=>'3','d'=>'2')
);
$data1 = $data2 = array();
foreach ($abc as $key => $value) {
$v1 = isset($value['a']) ? $value['a'] : 0;
$v2 = isset($value['b']) ? $value['b'] : 0;
if ($v1 == 1 && $v2 == 2) {
$data1[] = $value;
}
if ($v1 == 3) {
$data2[] = $value;
} ??
}
print_r($data1);
print_r($data2);
------解决方案--------------------
<?php
$abc = array(
'a1'=>array('a'=>1,'b'=>1,'c'=>1,'d'=>2),
'a2'=>array('a'=>1,'b'=>2,'c'=>2,'d'=>2),
'a3'=>array('a'=>3,'b'=>2,'c'=>3,'d'=>2)
);
$n = array();
foreach($abc as $key=>$val){
if($val['a']==1 && $val['b']==1
------解决方案--------------------
$val['a']==3){
$n = array_merge($n,array_values($val));
}
}
print_r($n);
?>
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 3
[5] => 2
[6] => 3
[7] => 2
)
------解决方案--------------------
$abc = array(
'a1' => array('a' => 1, 'b' => 1, 'c' => 1, 'd' => 2),
'a2' => array('a' => 1, 'b' => 2, 'c' => 2, 'd' => 2),
'a3' => array('a' => 3, 'b' => 2, 'c' => 3, 'd' => 2),
);
$new_arr1=array();
$new_arr2=array();
$item1=array('a'=>1,'b'=>1);
$item2=array('a'=>3);
foreach($abc as $k=>$v){
$a=array_intersect_assoc($item1,$v);
$b=array_intersect_assoc($item2,$v);
if($a==$item1) $new_arr1=$v;
if($b==$item2) $new_arr2=$v;
}
print_r(array_merge(array_values($new_arr1),array_values($new_arr2)));