php - Json_encode-将数组转换为json对象

标签 php arrays json

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

关于php - Json_encode-将数组转换为json对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21209386/

相关文章:

php - 页面在 Wamp 上显示但在真实服务器上出错

php - Mysql 没有选择数据库报错

php - 使用 CSS 为数据库查询集数据中的某些表行设置样式

ios - 使用 Array 中的 pathExtension 作为 TableViewCell 图像源

JavaScript setTimeout() 和数组

java - JSON 数据限制

c# - 序列化嵌套对象 (json.net)

php - Facebook 照片添加标签方法不起作用

arrays - 使用单指令填充 VB6 列表框

java - 光束json解析