2014-01-18 218 views
2

我目前正在從mysql表中獲取值。這些值是從foreach循環中抓取的。然後,循環完成後,數組被轉換成json對象。但是,爲了與其他API一起使用,我無法獲得json格式。有兩個時,我的循環只顯示一個結果。此外,我有一個函數返回一個十六進制值,當我在循環中調用它時返回null。我怎樣才能得到以下格式的值?Json_encode - 將數組轉換爲json對象

header("Content-type: application/json"); 
//get the course list 
$education_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt 
FROM academy a 
GROUP BY a.type"); 
$education_query->execute(); 
$data = $education_query->fetchAll(); 
$output = array(); 
foreach ($data as $row) { 
    //$type = ; 
    $output["valueField"] = $row["type"]; 
    $output["name"] = $row["type"]; 
    $output["color"] = hexcode(); 

} // foreach ($data as $row) { 
echo json_encode(array($output)); 

當前結果:

[{"valueField":"Upper-Secondary","name":"Upper-Secondary","color":null}] 

所需的結果:

[{ 
    valueField: "Post-Secondary", 
    name : "Post-Secondary", 
    color: "#40ae18" 
}, 
{ 
    valueField: "Upper-Secondary", 
    name : "Upper-Secondary", 
    color: "#aaab4b" 
}] 

EDIT(添加十六進制編碼功能):

function hexcode() 
{ 

$min = hexdec("000000"); // result is 0 and sets the min-value for mt_rand 
$max = hexdec("FFFFFF"); // result is 16777215 and sets the max-value for mt_rand 

$random = mt_rand($min, $max); // creates a radom number between 0 and 16777215 

$random_hex = dechex($random); // transforms the random number into a Hex-Code 

// now the test, if the result has 6 chars 

if (strlen($random_hex) != "6") // sometimes it returns an only 5, or less, char Hex-Code, 
    hexcode();  // so the function has to be repeat 
else 
    echo $random_hex; // returns the Hex-Code 
} 
+0

要返回遞歸調用'返回十六進制編碼()的結果;'。 –

+0

@AleksanderBavdaz是的,正確的。 – techAddict82

回答

3

您的循環正在顯示一個結果,因爲您每次都覆蓋數組鍵。

你可以改變這些三線

 $output["valueField"] = $row["type"]; 
     $output["name"] = $row["type"]; 
     $output["color"] = hexcode(); 

 $output[]["valueField"] = $row["type"]; 
     $output[]["name"]  = $row["type"]; 
     $output[]["color"]  = hexcode(); 

你可以張貼十六進制編碼()函數?

編輯

不需要所有這些代碼,你可以使用這個:

function hexcode(){ 
     return sprintf("#%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255)); 
    } 
+0

是的,我剛剛添加了十六進制()函數 – techAddict82

+0

我也編輯了迴應 –

3

$output需要是數組的數組。

$addToOutput = array(); 
$addToOutput["valueField"] = $row["type"]; 
// add other fields 
$output[] = $addToOutput; 
+0

謝謝,如何處理十六進制功能?它一直返回'null'。我只是想爲每個返回一個隨機的十六進制值。 – techAddict82