user1434156
user1434156

Reputation:

Json_encode - converting an array into a json object

I am currently fetching values from mysql table. The values are grabbed from a foreach loop. Then after the loop is done the array is converted into a json object. But I am having difficulties getting the json format in order to use with another api. My loop only display one result when there are two. Also I have a function that returns a hexadecimal value which is returning null when I call it inside the loop. How could I get those values in the format shown below?

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

Current Result:

[{"valueField":"Upper-Secondary","name":"Upper-Secondary","color":null}]

Desired Result:

[{
    valueField: "Post-Secondary",
    name :  "Post-Secondary",
    color: "#40ae18"
},
{
    valueField: "Upper-Secondary",
    name :  "Upper-Secondary",
    color: "#aaab4b"
}]

EDIT(adding hexcode function):

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
}

Upvotes: 0

Views: 724

Answers (2)

Amine Matmati
Amine Matmati

Reputation: 283

your loop is displying one results because you're overwriting the array keys every time.

you can change those 3 lines

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

to

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

can you post the hexcode() function ?

EDIT

no need for all this code, you can use this :

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

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

$output needs to be an array of arrays.

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

Upvotes: 2

Related Questions