Jump to content

How to return number of distinct elements in PHP array


marmite

Recommended Posts

Hi,

 

I need to structure a table differently depending whether the card is available only with one inside (e.g. blank) or whether it's available with two (e.g. blank & happy birthday).

 

I have an SQL query returning the message, so I want to check whether there is more than one distinct value in an array. The array exists already (e.g. $row['message']). Does anyone know a suitable function for this? Like, count_distinct_results...

 

 

(Originally I started off struggling with a separate SQL, which didn't seem to return the expected number:

 

$query4="select count(card_msg) from xyz where image_id='$id2'";
$result4=mysql_query($query4) or die ("Error in query " . mysql_error());
$row4=mysql_fetch_assoc($result4);

)

 

Thanks!

Maybe something like this?:

<?php
function array_csort($array){
$new_array = array();
foreach($array as $val){
	if(in_array($val,$new_array)){
		array_push($new_array,$val);
	}else{
		continue;
	}
}
return count($new_array);
}


$my_array = array(1,1,1,2,32,3,4,4,35,45,3,3,23,2,3,345,43);

echo array_csort($my_array);
?>

OK, so array_unique should work.

 

But this code will not work: it returns 1 even when there are 2 different messages returned. Print_r returns "resource id 6", and echo returns 1. Grateful for help....

 

$count="SELECT packaging_message from `abc` where packaging_message in (SELECT card_message from xyz where card_image_id='$id2')";

$count1=mysql_query($count) or die ("Error in query " . mysql_error());
print_r($count1);
echo count (array_unique($count1));

1 ) You'll find a join is much faster than a subquery

2 ) When you do it in the query with COUNT(DISTINCT) why bother with the array?

3 ) you haven't processed the query results to put the messages in an array

<?php
$msgArray = array();
$count1=mysql_query($count) or die ("Error in query " . mysql_error());
while ($row = mysql_fetch_row($count1)) {
     $msgArray[] = $row[0];                          // store messages in the array
} 
echo count (array_unique($msgArray));

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.