0

how can I save values in Arry's for each index? can I do it with Sql statement or loop? my mssql statement:

 $statement = "SELECT DISTINCT cat_id,value FROM mydb where cat_id > '3000' and cat_id < '6000' order by  cat_id";

display my results:

 foreach($Sitesresults as $row)
    {
 printf("<tr><td>%s</td>     <td>%s</td>/tr>",$row['cat_id'],$row['value']);            
    }

I'm getting the following table:

### cat_id ### value
3000, 100

3000, 200

3000, 300

3000, 400   

4000, 100

4000, 300

5000, 100

5000, 200

5000, 300

5000, 400   

5000, 500

5000, 600

I wold like to save values of each cat_id as Array and display them as follow:

### cat_id ### value
3000, 100,200,300,400

4000, 100,300

5000, 100,200,300,400,500,600

2 Answers 2

4

You can use GROUP_CONCAT in MySQL for that

SELECT cat_id, group_concat(distinct value) as values
FROM mydb 
where cat_id > '3000' and cat_id < '6000'
group by cat_id
order by cat_id
Sign up to request clarification or add additional context in comments.

2 Comments

that why I used DISTINCT in my statement
then use group_concat(distinct value) as values
0

If what you're trying to do, is add the values to an array [rather than display it], then you'll need to adjust your loop:

$container = array();
foreach ($Sitesresults as $row)
{
    $key = strval($row['cat_id']);
    if (!isset($container[$key]))
    {
        $container[$key] = array();
    }
    $container[$key][] = $row['value'];
}

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.