Itz Shovon
Itz Shovon

Reputation: 25

Show two MySQL column as key and value in JSON format

I want to show this MySQL table data in JSON object format with _key column as key and _value column as value. mysql table data

How can I do this with PDO in PHP?

I tried like this:

$info_arr = array();

while ($row = $result->fetch(PDO::FETCH_ASSOC))
    $info_arr[] = $row;
echo json_encode($info_arr);

But this gives me like this:

[
{
    "_key": "app_name",
    "_value": "Mathology"
},
{
    "_key": "app_package",
    "_value": "com.shovon.mathology"
},
{
    "_key": "app_version",
    "_value": "1.0"
},
{
    "_key": "app_icon",
    "_value": "com.shovon.mathology"
}
]

But I want to get result like this:

[
 {
     "app_name": "Mathology",
     "app_package": "com.shovon.mathology",
     "app_version": "1.0",
     "app_icon": "com.shovon.mathology"
 }
]

Upvotes: 1

Views: 171

Answers (1)

Dharman
Dharman

Reputation: 33238

echo json_encode($result->fetchAll(\PDO::FETCH_KEY_PAIR));

Output:

{
    "app_name": "Mathology",
    "app_package": "com.shovon.mathology",
    "app_version": "1.0",
    "app_icon": "com.shovon.mathology"
}

I don't know why would you want to put a single object in a JSON array. My solution outputs just the object. If you want to wrap it in an array then just put it inside of [] before sending to json_encode()

echo json_encode([$result->fetchAll(\PDO::FETCH_KEY_PAIR)]);

Upvotes: 1

Related Questions