mardi 21 juin 2016

Generating Key/value pairs for JSON format string Array in PHP

I am looping through a column in my localhost MySql table. I am able to print all the values in this table. My goal is turn these values into JSON format so that my android app could read and populate a ListView with them. I seem to be having the problem in setting up the "key" values in my key/values pair required to format a JSON string. I don't know how to use the while loop in order to create these json_encode array with key/values pair in it.

Here's what I have tried so far:

It works but I want my while loop to assign the key/value pairs and create the JSON string so my app could upload it to a ListView.

//all connections to database have been established
$hold = "select email from info";
$h = mysqli_query($connection,$hold);
$a = array();
$d = 0;

while($row = mysqli_fetch_array($h)){
    echo $d.'<pre>'.$row['email'].'<pre>';//this works fine
    $a[d] = $row['email']; //values have been assigned to array that will be    
    //converted to JSON format, but how can I assign the "key" to each value
    //now inside here it says that 'd' is an undefined constant. What could be
    //wrong with the scope of 'd'?
    $d++;
}

Once the keys have been assigned, I just need to convert the array to json format with json_encode(). On my android app, I would retrieve these key/value pairs. So somehow, my app code needs to know what "key" was assigned inside the while loop. It could be keys that are alphabetized so I could follow an ordering that would help me retrieve the values.

If you have any thoughts or ideas please advise.

Thank you

Aucun commentaire:

Enregistrer un commentaire