一个有关数组的问题(自我感觉有点难)
本帖最后由 mafeifan 于 2013-07-10 11:02:33 编辑 已知
$items = array(
array('dna_id'=>55,'status'=>1),
array('dna_id'=>55,'status'=>0),
array('dna_id'=>56,'status'=>1),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0)
);
array(
'active'=>array('count'=>3,'ids'=>array('55','58','60')),
'completed'=>array('count'=>1,'ids'=>array('56'))
);
$items = array(Array
array('dna_id'=>55,'status'=>1),
array('dna_id'=>55,'status'=>0),
array('dna_id'=>56,'status'=>1),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
);
$res = array(
'active'=> array(
'count' => 0,
'ids' => array()
),
'completed' => array(
'count' => 0,
'ids' => array()
),
);
foreach($items as $v) {
if(!in_array($v['dna_id'], $res['active']['ids'])) $res['active']['ids'][] = $v['dna_id'];
if($v['status']) {
if(!in_array($v['dna_id'], $res['completed']['ids'])) $res['completed']['ids'][] = $v['dna_id'];
}else $res['completed']['ids'] = array_diff($res['completed']['ids'], array($v['dna_id']));
}
$res['active']['ids'] = array_diff($res['active']['ids'], $res['completed']['ids']);
$res['active']['count'] = count($res['active']['ids']);
$res['completed']['count'] = count($res['completed']['ids']);
print_r($res);
foreach($items as $v){
$arr[$v['dna_id']][]=$v['status'];
}
print_r($arr);
foreach($arr as $k=>$v){
if($v==array_filter($v,'foo')){
$ar['completed']['count']++;
$ar['completed']['ids'][]=$k;
}else{
$ar['active']['count']++;
$ar['active']['ids'][]=$k;
}
}
print_r($ar);
function foo($v){
return $v==1;
}
<?php
$items = array(
array('dna_id'=>55,'status'=>1),
array('dna_id'=>55,'status'=>0),
array('dna_id'=>56,'status'=>1),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>58,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0),
array('dna_id'=>60,'status'=>0)
);
$ar=array();
$arr=array();
foreach($items as $k=>$v){
if (!in_array($v['dna_id'], $arr) && $v['status']===0) $arr[]=$v['dna_id'];
if (!in_array($v['dna_id'], $ar)) $ar[]=$v['dna_id'];
}
$a=array_diff($ar,$arr);
$c1=count($arr);
$c2=count($a);
$o=array(
'active'=>array('count'=>$c1,'ids'=>$arr),
'completed'=>array('count'=>$c2,'ids'=>$a)
);
var_export($o);
?>
foreach($items as $v){
$arr[$v['dna_id']][]=$v['status'];
}
array_walk($arr, function(&$v, $k) { $v = count($v) == array_sum($v) ? 1 : 0; });
$res = array(
'active'=> array( 'count' => count(array_keys($arr, 0)), 'ids' => array_keys($arr, 0) ),
'completed' => array( 'count' => count(array_keys($arr, 1)), 'ids' => array_keys($arr, 1) ),
);