4

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

    ?>
2
  • post here what you got Commented Dec 24, 2015 at 4:54
  • [{"Child Care":"After Scool,Breakfast Club\n"},{"Child Care":"Breakfast Club"}] Commented Dec 24, 2015 at 4:57

3 Answers 3

3

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); 
Sign up to request clarification or add additional context in comments.

6 Comments

Pleasure mate @SaiKumar
If I have 7 Coloumns like 'Childcare' what can i do @Darren
How exactly do you want the data to be passed through?
I have 7 Columns in a table i want get like [{ "Childcare":[ "All of Childcare", "After school",] "Classes":[ "All of Classes", "Antenatal",].........}
Ya Got it tnq @darren
|
1

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 Comment

No its getting error like <b>Notice</b>: Undefined offset: 0 in <b>C:\xampp\htdocs\activitytype.php</b> on line <b>9</b><br /> {"Childcare":[null,null]}
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.