在Php中构建具有多个参数的Json数组

时间:2012-03-19 07:09:50

标签: php arrays json

我设法在Json数组中输出了'resort'列,但我也需要'country',以及'aantal'。不知道该怎么做。有人可以帮助我吗?

if ($numrows < 1 && strlen($sq) > 3)
{
        $sql = "SELECT resort, country, COUNT(image) AS aantal FROM sx_cam
          LEFT JOIN sv_orte ON sv_cam.res_id = sv_orte.res_id
          WHERE sound=soundex('$sq') and (status < 1) GROUP BY resort order by aantal desc";
        $result2 = mysql_query($sql) or die(mysql_error());
        $numrows = mysql_num_rows($result2);
        $suggest = 2;
}

$items = array();

while($row = mysql_fetch_assoc($result2)){
 $items[$row['resort']] = $row['resort'];
}

foreach ($items as $key=>$value) {
 echo strtolower($key)."|$value\n";
}

1 个答案:

答案 0 :(得分:1)

你正在以错误的方式构建数组。一旦你掌握了数组,就像拨打json_encode

一样简单

我不完全确定你希望你的json看起来如何,但这样的事情应该让你开始

$items = array();

while($row = mysql_fetch_assoc($result2)){

    //first we build an 'object' of the current result
    $item['country'] = $row['country'];
    $item['resort'] = $row['resort'];

    //now push it on the array of results
    $items[] = $item;
}

echo json_encode($items);

一旦上述代码正常工作,您可以调整PHP数组以更改JSON的结构以满足您的需求。