vote up 1 vote down star

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

flag

Can you show a little more code? I guess you have a loop somewhere, it would help to see it. – deceze Apr 18 at 23:10

3 Answers

vote up 2 vote down check

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.

link|flag
thanks you for your time ;) – Tristan Apr 18 at 23:37
vote up 1 vote down

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.

link|flag
i could have work, but it's not, i've found another solution, thanks for helping ;) – Tristan Apr 18 at 23:36
vote up 1 vote down

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.

link|flag
thanks, your solution is similar to the previous one and it worked – Tristan Apr 18 at 23:37

Your Answer

Get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.