Jump to content

[SOLVED] Count Values in an array


crotech

Recommended Posts

I have been looking at the PHP documentation and can't figure out the best method to count the frequency of values in an array. $fields is returned from a MySQL query and would look something like the following:

 

$fields = array (   array(  'id'     =>    '1',
                            'type'   => 'text',
                            'height' =>  '100',
                            'width'  =>  '300'
                            ),                            
                    array(  'id'     =>     '2',
                            'type'   =>  'text',
                            'height' =>   '200',
                             'width' =>   '200'
                             ),
                    array( 'id'      =>     '3',
                           'type'    => 'image',
                           'height'  =>   '150',
                           'width'   =>   '300'
                           ),
                    array( 'id'      =>     '4',
                           'type'    => 'image',
                           'height'  =>   '400',
                           'width'   =>   '400'
                           ),
                    array( 'id'      =>      '5',
                           'type'    =>   'logo',
                           'height'  =>    '150',
                           'width'   =>    '150'
                           )
                    );

 

I need to return 3 values from the array: The number of fields of type 'text', 'image', and 'logo'. I'm new to multidimensional arrays and I'm having a hard time figuring out the best way to accomplish this.

 

Thanks for any help!

Link to comment
https://forums.phpfreaks.com/topic/83367-solved-count-values-in-an-array/
Share on other sites

Something like this should work.

 

$text = 0;
$image = 0;
$logo = 0;

foreach($fields as $array){
foreach($array as $key => $value){
   if($value == $text){
      $text++;
   }
   if($value == $image){
      $image++;
   }
   if($value == $logo){
     $logo++;
   }
}
}

 

 

I don't think there is a built in function to achieve this. You would just need to create a simple function:

 

<?php

function countValues($array) {
 $count = array();
 foreach ($array as $value) { $count[$value['type']]++; }
 return $count;
}


$valueCount = countValues($fields);

?>

 

Using the array in your post $valueCount would have the following values:

 

array(
   'text'     =>    2,
   'image'   => 2,
   'logo' =>  1
   ),

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.