Jump to content

[SOLVED] Counting Values in an Array()


JSHINER

Recommended Posts

Array
(
    [0] => Array
        (
            [0] => apple
            [1] =>  ball
            [2] =>  tiger
        )

    [1] => Array
        (
            [0] => ball
            [1] =>  square
            [2] =>  tiger
            [3] =>  apple
        )

    [2] => Array
        (
            [0] => ball
            [1] =>  tire
            [2] =>  square
        )
)

 

From that I want to create an array that counts how many of each word exists. To display as this:

 

array('apple' => 2, 'ball' => 3, 'tiger' => 2, 'square' => 2, 'tire' => 1)

 

How can I do this?

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

$testArray = array(	array( 'apple', 'ball', 'tiger'),
				array( 'ball', 'square', 'tiger', 'apple'),
				array( 'ball', 'tire', 'square'),
				'square'
			  );

function flattenArray($array) {
if(!is_array ( $array ) ){
	$array = array ( $array );
}

$arrayValues = array();

foreach ($array as $value) {
	if (is_scalar($value)) {
		$arrayValues[] = $value;
	} elseif (is_array($value)) {
		$arrayValues = array_merge($arrayValues, flattenArray($value));
	} else {
		$arrayValues[] = $value;
	}
}
return $arrayValues;
}


$wordCounts = array_count_values(flattenArray($testArray));

print_r($wordCounts);

You could try using ltrim.

 

 

$testArray = array(	array( 'apple', 'ball', 'tiger'),
				array( 'ball', 'square', 'tiger', 'apple'),
				array( 'ball', 'tire', 'square'),
				'square'
			  );

function flattenArray($array) {
if(!is_array ( $array ) ){
	$array = array ( $array );
}

$arrayValues = array();

foreach ($array as $value) {
	if (is_scalar($value)) {
		$arrayValues[] = ltrim($value);
	} elseif (is_array($value)) {
		$arrayValues = array_merge($arrayValues, flattenArray(ltrim($value)));
	} else {
		$arrayValues[] = ltrim($value);
	}
}
return $arrayValues;
}


$wordCounts = array_count_values(flattenArray($testArray));

print_r($wordCounts);

Ok another quick question.

 

That outputs:

 

Array
(
    [apple] => 2
    [ball] => 3
    [tiger] => 2
    [square] => 2
    [tire] => 1
)

 

How can I get it to go into an array:

 

$terms[] = array('term' => $term, 'counter' => $counter);

 

Where obviously 'term' is ball, square, etc and 'counter' is the # for that?

 

$newWordCounts = array();
foreach($wordCounts as $word => $count) {
   $newWordCounts[] = array('term'    => $word,
                            'counter' => $count
                           );
}
print_r($newWordCounts);

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.