How to get JSON data in the correct format using PHP

I am developing an IOS application, and for the API I am sending my requests to a URL that should return JSON data using PHP I get as

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

But I want to get

[{

"Childcare":[

"All of Childcare",

"After school",

"Breakfast Club"
]}

My code

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

    ?>
+4
source share
3 answers

Just put it in an array JSON.

$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 the 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); 
+3
source

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)); 
+1
source

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 function explode

0
source

Source: https://habr.com/ru/post/1621571/


All Articles