我目前正在从mysql表中获取值。这些值是从foreach循环中获取的。然后,在完成循环之后,将数组转换为json对象。但是我很难获得json格式以便与其他api一起使用。我的循环仅在有两个结果时显示一个结果。我也有一个返回十六进制值的函数,当我在循环内调用它时,它返回null。如何获得以下所示格式的值?
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"
}]
编辑(添加十六进制代码功能):
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
}
您的循环显示一个结果,因为您每次都覆盖数组键。
你可以改变那三行
$output["valueField"] = $row["type"];
$output["name"] = $row["type"];
$output["color"] = hexcode();
至
$output[]["valueField"] = $row["type"];
$output[]["name"] = $row["type"];
$output[]["color"] = hexcode();
您可以发布hexcode()函数吗?
编辑
不需要所有这些代码,您可以使用以下代码:
function hexcode(){
return sprintf("#%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句