开发者

PHP array : simple question about multidimensional array

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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜