2017-06-21 154 views
0

我有一個數組,並希望將一些靜態值添加到數組中,並獲得JSON中的預期結果。PHP的Mysql結果到JSON

原始數組:

$results= 
array (
    0 => 
    array (
    'country' => 'SG ', 
    'id' => '1 ', 
    'name' => 'jerome ', 
    'course1' => 'IT ', 
    'course2' => 'Music ', 
), 
    1 => 
    array (
    'country' => 'US ', 
    'id' => '2 ', 
    'name' => 'cindy ', 
    'course1' => 'IT ', 
    'course2' => 'Music ', 
), 
); 

預期JSON結果:

{ 
    "SG":{ 
    "name":"jerome", 
    "id":"1", 
    "Course":[ 
    { 
     "hall1":"IT" 
    }, 
    { 
     "hall2":"Music" 
    } 
    ] 
}, 
    "US":{ 
    "name":"cindy", 
    "id":"2", 
    "Course":[ 
    { 
     "hall1":"IT" 
    }, 
    { 
     "hall2":"Music" 

    } 
    ] 
} 
} 

我試圖用這個來呼應數組轉換成JSON,但未能得到預期的結果

foreach ($results as $result){ 
    $data[]=array(
     $result['country']=>array(
     "name"=>$result['name'], 
     "id"=>$result['id'], 
     "Course"=>array(
     "hall1"=>$result['course1'], 
     "hall2"=>$result['course2'] 
     ) 
    ) 
    ); 
    } 
echo json_encode($data); 

結果:

[ 
{ 
    "SG":{ 
    "name":"jerome", 
    "id":"1", 
    "Course":{ 
     "hall1":"IT", 
     "hall2":"Music" 
    } 
    } 
}, 
{ 
    "US":{ 
    "name":"cindy", 
    "id":"2", 
    "Course":{ 
     "hall1":"IT", 
     "hall2":"Music" 
    } 
    } 
} 
] 
+0

看看這個https:// stackov erum.com/questions/4064444/returning-json-from-a-php-script(我無法評論) – Richard

回答

1

在這裏,我對您的當前代碼一些改變,使其工作如預期內的陣列。

Try this code snippet here

foreach ($results as $result){ 
    $data[$result['country']]=//added country as index. 
     array(
     "name"=>$result['name'], 
     "id"=>$result['id'], 
     "Course"=>array(
     array("hall1"=>$result['course1']),//surrounded it by array 
     array("hall2"=>$result['course2'])//surrounded it by array 
     ) 
    ); 
} 
echo json_encode($data,JSON_PRETTY_PRINT); 
+0

我希望你將預期的輸出包裝在一個數組中以便於數據檢索,因爲他預期的json結果似乎沒有有這個。 @Sahil Gulati – KBJ

+0

做或不​​做。沒有「嘗試」。一個好的答案***將總是解釋所做的事情以及爲什麼這樣做,不僅是爲了OP,還是爲了將來訪問SO。 –

+1

@SahilGulati你歡迎老闆 – KBJ

0

使數組

"Course"=>array(
     array("hall1"=>$result['course1']), 
     array("hall2"=>$result['course2'])) 
0

下面的代碼片段是剛剛更新了你的代碼,你想通過這樣的 json_encode($data,JSON_FORCE_OBJECT)

編碼JSON可以實現響應的版本,但它會使JSON對象只讓你Course Array也將變成JSON對象

foreach ($results as $result){ 
    $arr[$result['country']] = [ 
     'name' => $result['name'], 
     'id' => $result['id'], 
     'Course' => [ 
      ['hall1' => $result['course1']], 
      ['hall2' => $result['course2']] 
     ] 
    ]; 

    $data[] = $arr; 
} 

echo json_encode($data);