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);
?>
Sai KumarSai Kumar
asked Dec 24, 2015 at 4:51
-
post here what you gotPathik Vejani– Pathik Vejani2015年12月24日 04:54:34 +00:00Commented Dec 24, 2015 at 4:54
-
[{"Child Care":"After Scool,Breakfast Club\n"},{"Child Care":"Breakfast Club"}]Sai Kumar– Sai Kumar2015年12月24日 04:57:22 +00:00Commented Dec 24, 2015 at 4:57
3 Answers 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);
answered Dec 24, 2015 at 5:06
Sign up to request clarification or add additional context in comments.
6 Comments
Darren
Pleasure mate @SaiKumar
Sai Kumar
If I have 7 Coloumns like 'Childcare' what can i do @Darren
Darren
How exactly do you want the data to be passed through?
Sai Kumar
I have 7 Columns in a table i want get like [{ "Childcare":[ "All of Childcare", "After school",] "Classes":[ "All of Classes", "Antenatal",].........}
Sai Kumar
Ya Got it tnq @darren
|
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));
answered Dec 24, 2015 at 5:05
1 Comment
Sai Kumar
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]}
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
answered Dec 24, 2015 at 5:05
Comments
default