从PHP多维数组中提取不同值的计数

时间:2013-12-16 14:55:30

标签: php arrays multidimensional-array

我有多维PHP数组数组

 $_SESSION['alldata'][0]["thisisval1"] = 1
 $_SESSION['alldata'][0]["markedval1"] = 1
 $_SESSION['alldata'][0]["herechcked"] = 1

 $_SESSION['alldata'][1]["thisisval1"] = 2
 $_SESSION['alldata'][1]["markedval1"] = 1
 $_SESSION['alldata'][1]["herechcked"] = 10

 $_SESSION['alldata'][2]["thisisval1"] = 1
 $_SESSION['alldata'][2]["markedval1"] = 0
 $_SESSION['alldata'][2]["herechcked"] = 1

 $_SESSION['alldata'][3]["thisisval1"] = 3
 $_SESSION['alldata'][3]["markedval1"] = 0
 $_SESSION['alldata'][3]["herechcked"] = 1

 $_SESSION['alldata'][4]["thisisval1"] = 2
 $_SESSION['alldata'][4]["markedval1"] = 1
 $_SESSION['alldata'][4]["herechcked"] = 7

所需要的是:

  1. 获取数组
  2. 中“thisisval1”的不同值列表
  3. 使用“thisvalval1”= 1
  4. 获取“markedval1”= 1的数组元素的计数

    目前我正在考虑在$ _SESSION ['alldata']上运行循环并获取上面所需的值; 是否有任何SMART方法可以做同样的事情?

1 个答案:

答案 0 :(得分:1)

 echo '<pre>';
 $newarray = array_values($arr);
 $i=0;
 $j=0;//thisisval1
 $distinctarray = array();
 foreach($newarray[0] as $k=>$v){

 if($v['thisisval1']){
    if(!in_array($v['thisisval1'],$distinctarray)){
    $distinctarray[] = $v['thisisval1'];
 }
 }

 if($v['thisisval1'] ==1){

 $i+=1;
 }elseif($v['markedval1'] ==1){
 $j+=1;
 }
 }
 echo 'count for thisisval1='.$i;
  echo 'count for markedval1='.$j;
 print_r($distinctarray);

输出

count for thisisval1=2
count for markedval1=2
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)