duanjing4623 2015-05-27 12:28
浏览 116
已采纳

转置返回的JSON对象(PHP,mySQL)

The object I get back from my sql query is a single row with about 50 columns. It returns an object like this:

[
    {
        "State": "Alabama",
        "State Abbrev": "AL",
        "County": "Madison",
        "FIPS": "01089",
        "msa": "3440",
        "msaname": "HUNTSVILLE, AL",
        "cbsa": "26620",
        "cbsaname": "Huntsville, AL",
        "Population": "346892",
        "Length of Life Rank": "4",
        "Quality of Life Rank": "6",
    }
]

What I need is a format like this:

[
{ “column”: “State”, “value”: “Alabama” },
 { “column”: “State Abbrev”, “value”: “AL” },
 ...
 ]

How can I transpose the result to match my requirements? I'm getting the data like so:

$sql4 = "SELECT d.* FROM `mytable` s 
INNER JOIN `secondtable` c ON 
c.`zip_code` = s.`zip_code` 
INNER JOIN `anothertable` d ON 
d.`fips` = c.`fips` 
WHERE s.`ID` = '{$prov_number1}' group by `ID`"; 
$result4 = $dbh->query($sql4)->fetchAll(PDO::FETCH_ASSOC);
$data['demo_info'] = $result4;
header('Content-type: application/json');
echo json_encode($data);

EDIT: some good answers, but I think my results are coming back wrong because my data is stuctured differently than what I have above. If I var_dump $result4, the structure is more like this:

array(1) {
  [0]=>
  array(93) {
    ["State"]=>
    string(7) "Alabama"
    ["State Abbrev"]=>
    string(2) "AL"
    ["County"]=>
    string(7) "Madison"
    ["FIPS"]=>
    string(5) "01089"
    ["msa"]=>
    string(4) "3440"
    ["msaname"]=>
    string(14) "HUNTSVILLE, AL"
    ["cbsa"]=>
    string(5) "26620"
}}

I'm thinking this might change the answers, as I've tried a few and get nothing in the "column" and all my data crammed into the "values".

  • 写回答

4条回答 默认 最新

  • douchang8219 2015-05-27 12:35
    关注
    $finalresult = array();
    $icount = 0 ;
    foreach($result4 as $row) {
         foreach ( $row as $key => $val ) {
    
            $finalresult[$icount]["column"] = $key;
            $finalresult[$icount]["value"] = $val;
            $icount++;
         }
    }   
    $data['demo_info'] = $finalresult;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用