Count multidimensional array

61 views Asked by At

I have my main array:

array(6) { 
    [1]=> array(3) { 
        [0]=> string(15) "Extension" 
        [1]=> int(1) 
        [2]=> string(6) "3,00 " 
    } 
    [2]=> array(3) { 
        [0]=> string(32) "Physics " 
        [1]=> string(1) "1" 
        [2]=> string(6) "3,00 " 
    } 
    [3]=> array(3) { 
        [0]=> string(31) "Physics " 
        [1]=> int(1) 
        [2]=> string(6) "6,00 " 
    } 
    [4]=> array(3) { 
        [0]=> string(34) "Desk" 
        [1]=> int(4) 
        [2]=> string(8) "127,00 " 
    } 
    [5]=> array(3) { 
        [0]=> string(18) "assistance" 
        [1]=> int(1) 
        [2]=> string(7) "12,50 " 
    } 
    [6]=> array(3) { 
        [0]=> string(15) "Extension" 
        [1]=> int(1) 
        [2]=> string(6) "3,00 " 
    } 
} 

My expected output is:

   Extension 2 
   Physics 2
   Desk 1 
   Assistance 1 

The result must be in an resultarray How can I do? I tried with array_count_values function but don't work.

How can I stock answear: I tried this code but It doesn't work

  $tabrecap = array();
  foreach($counts as $key=>$value){
   //echo $key." qte".$value;
  $tabrecap = array ($key,$value,$valueOption);
  }
3

There are 3 answers

3
Death-is-the-real-truth On BEST ANSWER

As you asked in comment,Please try this:-

<?php
$array =   array( '1'=> array('0'=>"Extension", '1'=> 1, '2'=>"3,00 " ), '2'=> array('0'=>"Physics",'1'=>"1","3,00 " ),'3'=> array('0'=>"Physics",'1'=>1,"6,00 "),'4'=> array('0'=>"Desk",'1'=>4,"127,00 "),'5'=> array('0'=>"assistance",'1'=>1,"12,50 " ),'6'=> array('0'=>"Extension",'1'=>1,"3,00 "));

$count = array();

$i = 0;

foreach ($array as $key=>$arr) {
  // Add to the current group count if it exists
  if (isset($count[$i][$arr[0]])) {
    $count[$i][$arr[0]]++;
  }
  else $count[$i][$arr[0]] = 1;

  $i++;
}
print_r($count);
 ?>

Output:- https://eval.in/379176

3
fdehanne On

Just make a loop and use first item of each array as key :

$array = array(
    array("Extension", 1, "3,00"),
    array("Physics", "1", "3,00"),
    array("Physics", 1, "6,00 ")
);
$count = array();

foreach($array as $a)
    $count[$a[0]]++;

var_dump($count); // array(2) { ["Extension"]=> int(1) ["Physics"]=> int(2) }
0
thelastshadow On

Looping is the answer.

<?php
// untested

$counts = Array();
foreach( $array as $subArray ){
    $value = $subArray[0];
    $counts[ $value ] = ( isset($counts[ $value ]) )
        ? $counts[ $value ] + 1
        : 1;
}

var_dump( $counts);