2014-01-18 220 views
2

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

要返回递归调用'返回十六进制编码()的结果;'。 –

+0

@AleksanderBavdaz是的,正确的。 – techAddict82

回答

3

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

你可以改变这些三线

 $output["valueField"] = $row["type"]; 
     $output["name"] = $row["type"]; 
     $output["color"] = hexcode(); 

 $output[]["valueField"] = $row["type"]; 
     $output[]["name"]  = $row["type"]; 
     $output[]["color"]  = hexcode(); 

你可以张贴十六进制编码()函数?

编辑

不需要所有这些代码,你可以使用这个:

function hexcode(){ 
     return sprintf("#%02X%02X%02X", mt_rand(0, 255), mt_rand(0, 255), mt_rand(0,255)); 
    } 
+0

是的,我刚刚添加了十六进制()函数 – techAddict82

+0

我也编辑了回应 –

3

$output需要是数组的数组。

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

谢谢,如何处理十六进制功能?它一直返回'null'。我只是想为每个返回一个随机的十六进制值。 – techAddict82