Sai Kumar
Sai Kumar

Reputation: 53

How to get JSON data in Correct format using PHP

I'm developing an IOS app, and for the API I'm sending my requests to a URL that should return JSON data with PHP I am Getting like

[{"Child Care":"After Scool,Breakfast Club\n"},{"Child Care":"Breakfast Club"}]

But I want to get like

[{

"Childcare":[

"All of Childcare",

"After school",

"Breakfast Club"
]}

My code is

    <?php
session_start();
$connection=mysqli_connect('localhost','root','','testing') or die(mysqli_error());

    $sql="select `Child Care` from Activity_type ";
    $result = mysqli_query($connection,$sql) or die("Error in Selecting " . mysqli_error($connection));
    $emparray=array();
    while($row =mysqli_fetch_assoc($result)){
        array_push($emparray,$row);
        }   
        header('Content-Type: application/json');
        echo json_encode($emparray); 

    ?>

Upvotes: 4

Views: 86

Answers (3)

Darren
Darren

Reputation: 13128

Simply put it in your JSON array properly.

$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
    $emparray['Child Care'][] = $row['Child Care'];
}

header('Content-Type: application/json');
echo json_encode($emparray); 

To answer your second question from the comments:

$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
    foreach($row as $key => $val) {
        $emparray[$key][] = $val;
    }
}

header('Content-Type: application/json');
echo json_encode($emparray); 

Upvotes: 3

Murali krishna
Murali krishna

Reputation: 823

This will give the format you want.Let me know if this works for you.

while($row =mysqli_fetch_assoc($result)){
    array_push($emparray,$row['Child Care']);
}   
header('Content-Type: application/json');
echo json_encode(array("Childcare" => $emparray)); 

Upvotes: 1

Double H
Double H

Reputation: 4160

Try something like,

$sql="select `Child Care` from Activity_type ";
$result = mysqli_query($connection,$sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray=array();

while($row =mysqli_fetch_assoc($result)){
    $cares = explode(',' $row['Child Care']);
    foreach($cares as $care){
      $emparray[] = $care;
  }
}   

header('Content-Type: application/json');    
echo json_encode($emparray); 

Use php explode function

Upvotes: 0

Related Questions