views:

105

answers:

3

Hello,

i've got a SQL query which returns multiple rows, and i have :

$data = array(
    "nom" => $row['nom'] ,
    "prix"   => $row['rapport'],
    "average"   => "$moyenne_ge"
  );

which is perfect, but only if my query returns one row.

i tried that :

$data = array();
$data[$row['nom']]["nom"] = $row['nom'] ;
...
$data[$row['nom']]['average']  = "$moyenne_ge";

in order to have :

$data[brand1][nom] = brand1
$data[brand1][average] = 150$
$data[brand2][nom] = brand2
$data[brand2][average] = 20$
...

but when i do : json_encode($data)

i only have the latest JSON object instead of all JSON object from my request as if my array has only one brand instead of 10.

I guess i did something stupid somewhere. Thanks for your help

+1  A: 

I guess something like this should work for you:

$resource = mysql_query("YOUR QUERY");
$results = array()

while($result = mysql_fetch_assoc($resource)) {
    $results[$result['brand']] = array(
        'nom' => $result['nom'],
        'prix' => $result['rapport'],
        'average' => $moyenne_ge
    );
)

$results now contains all the rows from the query indexed by brand. Ask in comments if this wasn't what you're looking for.

Tatu Ulmanen
i could have work, but it's not, i've found another solution, thanks for helping ;)
Tristan
+1  A: 

If I am reading you right, you should just have to do something like this:

$data[] = array(
    "nom" => $row['nom'] ,
    "prix"   => $row['rapport'],
    "average"   => "$moyenne_ge"
);

(notice the [])

This should append each array onto $data instead of overwriting the contents.

W_P
thanks, your solution is similar to the previous one and it worked
Tristan
+2  A: 

I'd guess that your line:

$data = array();

Is initializing the array on each iteration of your loop. You aren't accumulating more than one row of data.

Bill Karwin
thanks you for your time ;)
Tristan