Wednesday, 29 August 2018

PHP displays the contents of the associative array in JSON format

I'm new in PHP language. I'm writing a PHP script to get information from my online database(created on my altervista personal webpage) and convert in JSON format. The problem is about when i get elements from my database i can show them correctly using "echo" command, but when i parse associative array to "json_encode" function i can't see correctly elements.

Here is the code:
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
$json_array = array();

if ($result->num_rows > 0) {
    // output data of each row
    $row = $result->fetch_assoc();
    foreach($row as $key => $value) {
        echo "" . $key . ": " . $value;
        echo "<br>";
        $json_array[] = array(''=>$key, ''=>$value);
    }
} else {
    echo "0 results";
}
echo json_encode($json_array);
$conn->close();
?>

The $result->fetch_assoc(); returns an associative array.
As i said before i can see correct information using echo commands.
The problem is when i use this:
$json_array[] = array(''=>$key, ''=>$value);

The output is as follow:
[{"":"Mark"},{"":"ABC"},{"":"25"}]

Basically it's showing me only the second parameter "=>$value", while the first parameter "=>$key" is ignored.
Can you tell me please what should i change in order to see also the first parameter in my output?
Thanks

The correct way would be to do that
$json_array[] = array( $key => $value );
instead of
$json_array[] = array(''=>$key, ''=>$value);
You are essentially adding an EMPTY string as key and the $key as value at first, and then you replace it with the $value as they share the EMPTY string key in the array.

0 comments:

Post a Comment