1

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
  • Can you show a little more code? I guess you have a loop somewhere, it would help to see it. Commented Apr 18, 2010 at 23:10

3 Answers 3

2

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.

0
1

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.

1
  • i could have work, but it's not, i've found another solution, thanks for helping ;) Commented Apr 18, 2010 at 23:36
1

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.

1
  • thanks, your solution is similar to the previous one and it worked Commented Apr 18, 2010 at 23:37

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.