0

how can i count or merge same data from the database? here is my code but this wont work..help please..

<?php
$result = mysql_query("SELECT category FROM inventory");

while($row = mysql_fetch_array($result)){
    $cat_array = array($row['category']);
    foreach ($cat_array as $value){
        if ($value<=1){
        echo $value . "</br>";
        }else{}
    }
}   
?>

and my output is this..how can i make same value echoed as one? or disregard the duplicate one..
  • speaker
    accessory
    lights
    tweeter
  • speaker
2
Contributors
2
Replies
11
Views
2 Years
Discussion Span
Last Post by mcdczzz
1

Try using an array and adding to it, that way we can check if there's a value already matching it.

<?php
$result = mysql_query("SELECT category FROM inventory");

$output = array();

while($row = mysql_fetch_array($result)){
    $cat_array = array($row['category']);
    foreach ($cat_array as $value){
        if ($value<=1 && !in_array($value,$output)){ # If $value is already in the array
            array_push($output,$value); # Add to array
        } # No need for 'else{}'
    }
}

foreach($output as $value){
    echo $value."<br/>";
}
?>
1

mattster..it is working :D thank you very much..i have to look for array_push though.. again thank you :)

Votes + Comments
No worries :)
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.