如何访问已连接的SQL表的列(对于JSON)

时间:2013-04-29 20:30:43

标签: php sql json

在我的PHP文件中,我正在运行以下SQL查询:

SELECT *   
FROM national_age_gender_demographics INNER JOIN arizona_age_gender_demographics
WHERE national_age_gender_demographics.age_group = arizona_age_gender_demographics.age_group
ORDER BY national_age_gender_demographics.index_number";

现在,我正在尝试使用以下内容访问行以创建JSON数据:

for ($i = 0; $i < $numRows; $i++) {
    if ($i != 0) {
        $tableData .= ",[";
    }
    $tableData .= '"' . $row['national_age_gender_demographics.age_group'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.both_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.male_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.female_pop'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.male_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.female_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.both_percent'] . '",';
    $tableData .= '"' . $row['national_age_gender_demographics.males_per_100_females'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.both_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.male_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.female_pop'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.male_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.female_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.both_percent'] . '",';
    $tableData .= '"' . $row['arizona_age_gender_demographics.males_per_100_females'] . '"]';
    if ($i != $numRows - 1) {
        $row = mysqli_fetch_array($result);
    }
}

在我的浏览器中输入PHP文件的URL时,我正在为我尝试访问连接表的每一行获取未定义的索引。

我想知道,访问连接表的正确语法是什么?不,不要告诉我使用json_encode,因为它会引发DataTables的JavaScript错误。

1 个答案:

答案 0 :(得分:0)

你不能在列名中有.所以我假设第一部分实际上是表的名称。在这种情况下,数组键是句点之后的部分:

$row['males_per_100_females']

如果您要输出JSON,您应该使用json_encode而不是手动编码。

$data = array(
   'some_key' => 'some data',
   'table_data' => array()
);

while(false !== ($row = $result->fetch_assoc())) {
   $data['table_data'][] = $row;
}

echo json_encode($data);