2

Hi I am trying to count the number of duplicate values in a associative array that looks like this:

array(3) { [0]=> array(3) { ["Title"]=> string(25) "hello" 
                            ["Price"]=> int(50) 
                            ["Count"]=> int(1) }
           [1]=> array(3) { ["Title"]=> string(35) "world" 
                            ["Price"]=> int(50) 
                            ["Count"]=> int(1) } 
           [2]=> array(3) { ["Title"]=> string(25) "hello" 
                            ["Price"]=> int(50) 
                            ["Count"]=> int(1) } } 

As you can see here there is a duplicate value in the "Title" lable I want to count them and add one to the "Count" part. I started to do something like this:

$prodArray = array();

// Add the values to the array if it's the first time it occurs.
if (!in_array($row['prodTitle'], $prodArray["Title"]))
{
array_push($prodArray, 
           array( Title => $row['prodTitle'],
                  Price => $row['prodPrice'],
                  Count => 1)
          );
}
else
{
//Add one to the count for the current item.
}   

the thing is I can't access the "Title" element in the array through the in_array function. Any suggestions are welcome.

dnagirl
  • 20,196
  • 13
  • 80
  • 123
user1593846
  • 734
  • 1
  • 15
  • 34
  • sort them and then running a foreach loop comparing one with the former and adding 1 to a counter every time it is equal ? – iaintunderstand Aug 12 '12 at 20:39
  • Do you have a example of how that would look? – user1593846 Aug 12 '12 at 22:11
  • well I am not an expert at all, but you know there are functions that do that, there is no need to invent anything. Here is the link to those functions http://php.net/manual/en/array.sorting.php – iaintunderstand Aug 13 '12 at 06:03
  • well I have gone trough some of those functions and i found something that might be usable, it looked something like the first example at this link, I just dont understand the code fully so would appreciate if anyone could explain the function for me. http://php.net/manual/en/function.uksort.php – user1593846 Aug 14 '12 at 11:35

2 Answers2

1

If you want to detect dups in an array that you are creating, something like this avoid having to go through the array multiple times:

$arr=array();
while($row = mysql_fetch_array($result))  {                  
  $arr[$row['prodTitle']] = isset($arr[$row['prodTitle']]) 
                               ? $arr[$row['prodTitle']] +1 
                               : 0;                    
}
$dups = array_keys(array_filter($arr)); //any key => 0 will be filtred out

If you want to just get the dups directly by SQL, have a look at this:

Your current query--

SELECT prodTitle 
  FROM product 
WHERE prodTitle != '{$keyword}' 
  AND creditCard IN( SELECT creditCard FROM product WHERE prodTitle ='{$keyword}');

which given data like this

prod cc
A    1
A    2
A    3
A    1
A    1
B    15
B    1
B    2
B    21
C    10
C    1

returns this set (with $keyword=='A'):

prod 
B
B
C

An aggregate query that returns only records where credit cards used on non-X were also used on X at least twice --

SELECT p1.prodTitle, COUNT(p2.creditCard) AS numrecords
  FROM product p1
    JOIN product p2
    ON (p1.creditCard = p2.creditCard)
WHERE p1.prodTitle != '{$keyword}'
  AND p2.prodTitle = '{$keyword}'
GROUP BY p1.prodTitle 
  HAVING COUNT(p2.creditCard) > 1;

given the same data, returns this set:

prod  num
B    2

Doing an aggregate query avoids all the messing about with loops. Here's a link to the MySQL list of aggregate functions.

dnagirl
  • 20,196
  • 13
  • 80
  • 123
0

Okey so I found my solution and I made it look something like this probably not he most efficient way but it works:

$prodArray = array();
$ar = array();


$query ="THE QUERY";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result))
{
array_push($ar, $row['prodTitle']);
}

function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}


$uniarr = array_unique($ar);

//Will run the function findDuplicates for each unique title in the array
for ($i = 0; $i < sizeof($uniarr); $i++)
{
$count = findDuplicates($ar, $uniarr[$i]);
array_push($prodArray, array( Title => $uniarr[$i], Count => $count));
}

//Displays 2 of the results in the array
for ($c = 0; $c < 2; $c++)
{
echo "The title:".$prodArray[$c]["Title"]." And the amount:".$prodArray[$c]["Count"];
echo "<br />";
}

So that's pretty much it feel free to post your comments on this and if you have any improvements feel free to post them.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user1593846
  • 734
  • 1
  • 15
  • 34
  • since you're doing a query, why not find the duplicates with the query rather than trying to find them in the resulting array? – dnagirl Aug 14 '12 at 17:14
  • I am not that good with SQL so i'm not sure how I would Count the number of duplicates and add the count and title to the array within the existing query I got. The query looks like this: $query ="SELECT prodTitle FROM product WHERE prodTitle != '{$keyword}' AND creditCard IN( SELECT creditCard FROM product WHERE prodTitle ='{$keyword}')"; – user1593846 Aug 14 '12 at 19:16