简体   繁体   中英

PHP Extract and count first elements of each element in multidimensional array

I have this array in php,

   $mainArray = array(
      array("apple","two", "grren"),
      array("samsung","five", "red"),
      array("microsoft","one","gray"),
      array("apple","nine", "blue"),
      array("samsung","ten", "white"),
      array("nokia","seven", "yellow")
   );

I can easily loop through it and extract all the first entries of each array like this:

 foreach($mainArray as $w => $n) {
  $whatever =  $mainArray[$w][0];
}

I'm trying to count how many entries are the same in the first element of each array, and have a result of something like:

apple (2)
samsung (2)
microsoft (1)
nokia (1)

I'm just not sure what is the correct way to do this.

Thank you in advance.

print_r(
    array_count_values(
        array_map('array_shift', $mainArray)
    )
);

Output ( Demo ):

Array
(
    [apple] => 2
    [samsung] => 2
    [microsoft] => 1
    [nokia] => 1
)

So even I am a big fan of foreach , why did I not use it here?

First of all, to count values in an array, in PHP we have array_count_values . It does the job for us.

So the only problem left was to get all the first items into an array to count them with array_count_values . That is a typical mapping job, and I like mapping, too, next to foreach so I tried if array_map together with array_shift worked - and it did.

However you might want to look for a function called array_column . It's not yet available with PHP itself, but as PHP code in another answer :

$counts = array_count_values(array_column($mainArray, 0));
$count = array();
foreach($mainArray as $array) {
    $first = $array[0];
    if(!isset($count[$first])) $count[$first] = 0;
    $count[$first]++;
}

print_r($count);

Collect every first element of the deep arrays by pushing them into a new array ( $result in my example) and then call array_count_values() on that array. Like so:

$mainArray = array(
  array("apple","two", "grren"),
  array("samsung","five", "red"),
  array("microsoft","one","gray"),
  array("apple","nine", "blue"),
  array("samsung","ten", "white"),
  array("nokia","seven", "yellow")
);

$result = array();
foreach( $mainArray as $k => $v )
{
    // let's continue if $v is not an array or is empty
    if( !is_array( $v ) || empty( $v ) ) continue;

    $result[] = $v[ 0 ];
}

var_dump( array_count_values( $result ) );

You can loop through the $mainArray to build a full array/list of values and then use array_count_values() on that:

$firstElements = array();
foreach ($mainArray as $arr) {
    $firstElements[] = $arr[0];
}
$counts = array_count_values($firstElements);

Another option would be to loop through $mainArray and insert the value as an index for an array (if it doesn't already exist) and then increment it each time (this will do the same thing as array_count_values() in the end):

$counts = array();
foreach ($mainArray as $arr) {
    if (!isset($counts[$arr[0]])) $counts[$arr[0]] = 0;
    $counts[$arr[0]]++;
}

You can do it just like this:

foreach($mainArray as $n) {
  $count[$n[0]] = isset($count[$n[0]]) ? $count[$n[0]]++ : 1;
}

var_dump($count); //should give you something like
/*
array(4) {
  ["apple"]=>
  int(2)
  ["samsung"]=>
  int(2)
  ["microsoft"]=>
  int(1)
  ["nokia"]=>
  int(1)
}
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM