繁体   English   中英

Json_encode-将数组转换为json对象

[英]Json_encode - converting an array into a json object

我目前正在从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必须是一个数组数组。

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

您的循环显示一个结果,因为您每次都覆盖数组键。

你可以改变那三行

      $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));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM