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

时间:2015-05-27 12:28:27

标签: php mysql json

我从sql查询中返回的对象是一行,大约有50列。它返回一个这样的对象:

[
    {
        "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",
    }
]

我需要的是这样的格式:

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

如何调整结果以符合我的要求?我得到的数据是这样的:

$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);

编辑:一些好的答案,但我认为我的结果是错误的,因为我的数据与我上面的数据结构不同。如果我var_dump $result4,结构更像是这样:

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"
}}

我认为这可能会改变答案,因为我已经尝试了一些并且没有在"栏中获得任何内容"并且我的所有数据都塞进了"值"。

4 个答案:

答案 0 :(得分:2)

使用foreach循环

$result = array();
$i = 0;
foreach($arr as $key => $value){
    $result[$i]['column'] = $key;
    $result[$i]['value'] = $value;
    $i++;
}
echo json_encode($result);

使用array_map

$result = array_map(function($k,$v){return array('column' => $k,'value' => $v);},  array_keys($arr),$arr);
echo json_encode($result);

DEMO

答案 1 :(得分:1)

$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;

答案 2 :(得分:1)

试试这个:

$data = json_decode( $json );
$result = array();
$n=0;
foreach($data[0] as $k=>$v) {
    $result[$n]['column'] = $k;
    $result[$n]['value'] = $v;
    $n++;
}
$result_json = json_encode( $result );

答案 3 :(得分:0)

简单地生成这样的数组并返回 -

$newArray = array_map(function($value, $key){
    return array('column' => $key, 'value' => $value);
}, $array, array_keys($array));

json_encode($newArray);