我目前正在從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
}
要返回遞歸調用'返回十六進制編碼()的結果;'。 –
@AleksanderBavdaz是的,正確的。 – techAddict82