从两个SQL表构造PHP关联数组

时间:2016-06-13 19:43:41

标签: php json postgresql

我正在使用PHP构建以下PostgreSQL查询

$sql = 'SELECT * FROM acs_14_5yr_2p05_senate;

使用以下While循环:

$rs = $conn->query($sql);
$acsjson = array('ACS'  => array());
while ($row = $rs->fetch(PDO::FETCH_ASSOC)) {
    $properties = $row;
    $feature = array(
        'geographicProfile' => $properties
    );
    array_push($acsjson['ACS'], $feature);
}

echo json_encode($acsjson, JSON_NUMERIC_CHECK);

返回以下JSON:

{"ACS":[
    {"geographicProfile":{
        "senateid":"610U400US27001",
        "geo_display":"State Senate District 01",
        "hc01_vc03":32525,
        "hc01_vc04":21032,
        "hc01_vc05":8869,
        "hc01_vc06":16853,
        "hc01_vc07":6042
    }},
    {"geographicProfile":{
        "senateid":"610U400US27002",
        "geo_display":"State Senate District 02",
        "hc01_vc03":31319,
        "hc01_vc04":22041,
        "hc01_vc05":8539,
        "hc01_vc06":17100,
        "hc01_vc07":5666
    }},
    {etc}, {etc}, {etc}
]}

“geographicProfile”中的键是神秘的Census字段名称。幸运的是,他们有一个单独的元数据表,其中以下查询具有类似的while循环:

$metasql = 'SELECT name, description FROM acs_14_5yr_senate_metadata';

返回

 {"metadata":[{"name":"hc01_vc03","description":"Estimate; HOUSEHOLDS BY TYPE - Total households"},
    {"name":"hc02_vc03","description":"Margin of Error; HOUSEHOLDS BY TYPE - Total households"},
    {"name":"hc03_vc03","description":"Percent; HOUSEHOLDS BY TYPE - Total households"},
    {"name":"hc04_vc03","description":"Percent Margin of Error; HOUSEHOLDS BY TYPE - Total households"}, 
    {etc}, {etc}]}

我想返回原始查询,其中隐藏的人口普查名称与嵌套JSON对象中的相应元数据值相关联,以显示“hc01_vcXX”字段的值和元数据描述:

{"ACS":[
    {"geographicProfile":{
       "senateid":"610U400US27001",
       "geo_display":"State Senate District 01",
       "hc01_vc03":[32525, metadataQuery['hc01_vc03']]
       "hc01_vc04":[21032, metadataQuery['hc01_vc04']]
       "hc01_vc05":[8869, metadataQuery['hc01_vc05']]
       "hc01_vc06":[16853, metadataQuery['hc01_vc06']]
       "hc01_vc07":[6042, metadataQuery['hc01_vc07']]
    }},
    {"geographicProfile":{
        "senateid":"610U400US27002",
        "geo_display":"State Senate District 02",
        "hc01_vc03":[31319, OtherQuery['hc01_vc03']]
        "hc01_vc04":[22041, OtherQuery['hc01_vc04']]
        "hc01_vc05":[8539, OtherQuery['hc01_vc05']]
        "hc01_vc06":[17100, OtherQuery['hc01_vc06']]
        "hc01_vc07":[5666, OtherQuery['hc01_vc07']]
    }}
    {etc},{etc}
]}

有人可以帮我在循环时构建PHP关联数组,还是为我的问题提供替代解决方案?我很少编写任何PHP,除了创建这样的小服务。

0 个答案:

没有答案