我目前正在从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