PHP 神奇De数组
$infos = array(
array(
'a' => 36,
'b' => 'gh',
'd' => '2015/08/42e3.png'
),
array(
'a' => 6,
'b' => 'jk',
'd' => '2015/08/43848.png'
),
array(
'a' => 36,
'b' => 'db',
'd' => '2015/08/5465.png'
),
array(
'a' => 6,
'b' => 'aw',
'd' => '2015/08/b3219929.png'
)
);
处理要求:将数组中某个相同键值的二维数组合并到一个数组中,生成一个新的数组。
$result= array();
foreach ($infos as $key => $info) {
$result[$info['a']][] = $info;
}
print_r($result);
$arr = Array
(
'0' => Array
(
's_id' => 79,
'num' => 1,
'date' => '2018-09-21'
),
'1' => Array
(
's_id' => 80,
'num' => 2,
'date' => '2018-09-21'
),
'2' => Array
(
's_id' =>80,
'num' => 1,
'date' => '2018-09-21'
),
'3' => Array
(
's_id' => 82,
'num' => 1,
'date' => '2018-09-22'
)
);
处理要求:将数组中相同字段下值合并求和,生成一个新的数组。
foreach($arr as $v){
if(!isset($ret[$v['s_id'].'_'.$v['date']])){
$ret[$v['s_id'].'_'.$v['date']] = $v;
}else{
$ret[$v['s_id'].'_'.$v['date']]['num'] += $v['num'];
}
}
print_r(array_values($ret));
效果如下
Array
(
[0] => Array
(
[s_id] => 79
[num] => 1
[date] =>2018-09-21
)
[1] => Array *Look at this*
(
[s_id] => 80
[num] => 3
[date] =>2018-09-21
)
[2] => Array
(
[s_id] => 82
[num] => 1
[date] => 2018-09-22
)
)
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => a
[1] => b
)
)
处理要求:将数组中相同的键取出,生成一个新的数组。
$arrNew=[];
$key=array_keys($arr);
foreach ($arr as $val){
foreach ($key as $k=>$v){
$arrNew[$k][]=$val[$v];
}
}
print_r($arrNew);
效果如下
Array
(
[0] => Array
(
[0] => 1
[1] => a
)
[1] => Array
(
[0] => 2
[1] => b
)
)