php 统计二维数组中某个相等值的总个数,并且组合成一个新的数组
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 统计二维数组中某个相等值的总个数,并且组合成一个新的数组相关的知识,希望对你有一定的参考价值。
比如这样的,我想将这个数组里面 m_id 相等数组元素再组合成一个新的数组:效果图如下:
$arr = array(array('sv_id'=>1,'mid_id'=>1,'sv_question'=>20),
array('sv_id'=>2,'mid_id'=>2,'sv_question'=>10),
array('sv_id'=>3,'mid_id'=>1,'sv_question'=>20),
array('sv_id'=>4,'mid_id'=>3,'sv_question'=>20),
array('sv_id'=>5,'mid_id'=>2,'sv_question'=>20),
);
foreach($arr as $k => $val)
if(!isset($tmp[$val['mid_id']]))
$tmp[$val['mid_id']][$val['sv_id']] = array( 'sv_id'=>$val['sv_id'], 'mid_id'=>$val['mid_id'], 'sv_question'=>$val['sv_question'], );
else
$tmp[$val['mid_id']][$val['sv_id']] = array( 'sv_id'=>$val['sv_id'], 'mid_id'=>$val['mid_id'], 'sv_question'=>$val['sv_question'], );
print_r($tmp);
#效果是一样,但是不理解“计算sv_qustion的总和”是什么意思追问
$sum = array();
foreach($tmp as $itme)
foreach($itme as $i)
$sum[$i['mid_id']]+= $i['sv_question'];
最后输出:
Array
(
[1] => 40
[2] => 30
[3] => 20
)
试着做出来了,前面的多谢你啦!!!嘎嘎
0=>array('sv_id'=>1,'mid_id'=>1,'sv_question'=>20),
1=>array('sv_id'=>3,'mid_id'=>2,'sv_question'=>20),
2=>array('sv_id'=>2,'mid_id'=>1,'sv_question'=>20)
);
function countArr($arr)
$arr2 = array();
foreach($arr as $k=>$v)
foreach($v as $k2=>$v2)
if(!isset($arr2[$k2][$v2]))
$arr2[$k2][$v2] = 1;
else
++$arr2[$k2][$v2];
return $arr2;
print_r(countArr($arr));
输出:
Array (
[sv_id] => Array ( [1] => 1 [3] => 1 [2] => 1 )
[mid_id] => Array ( [1] => 2 [2] => 1 )
[sv_question] => Array ( [20] => 3 ) )追问
foreach()
if()
$temp=
大概就这样吧!追问
可是,if 里面的条件怎么判断呀
追答 $arr = array(0=>array('sv_id'=>1,'m_id'=>1,'sv_question'=>20),
1=>array('sv_id'=>3,'m_id'=>2,'sv_question'=>20),
2=>array('sv_id'=>2,'m_id'=>1,'sv_question'=>20),
3=>array('sv_id'=>4,'m_id'=>3,'sv_question'=>20),
4=>array('sv_id'=>5,'m_id'=>2,'sv_question'=>20)
);
function countArr($arr)
$temp=array();
foreach($arr as $k=>$v)
$temp[$v['m_id']][$v['sv_id']]=$v;
return $temp;
print_r(countArr($arr));
PHP获取二维数组中相同的元素
比如
array(array('id' => '10'),array('id' => '2'),array('id' => '10'),array('id' => '3'),array('id' => '2'))
怎么获取这个二维数组中相同id的数组有几个。id是多少啊!
$ids = array();
foreach($a as $k=>$v)
foreach($v as $value)
if(!in_array($value,$ids))
$ids[] = $value;
foreach($a as $k=>$v)
foreach($v as $value)
foreach($ids as $key=>$id)
if($id == $value)
$res[$key]['id'] = $id;
$res[$key]['num']++;
print_r($ids);
print_r($res);
Array
(
[0] => 10
[1] => 2
[2] => 3
)
Array
(
[0] => Array
(
[id] => 10
[num] => 2
)
[1] => Array
(
[id] => 2
[num] => 2
)
[2] => Array
(
[id] => 3
[num] => 1
)
)本回答被提问者采纳
以上是关于php 统计二维数组中某个相等值的总个数,并且组合成一个新的数组的主要内容,如果未能解决你的问题,请参考以下文章