Look for duplicate values in a associative array and add them to a count

后端 未结 2 1352
梦谈多话
梦谈多话 2021-01-22 01:17

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) \"         


        
2条回答
  •  面向向阳花
    2021-01-22 02:01

    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 "
    "; }

    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.

提交回复
热议问题