Need to merge many rows in one JSON - php

How to make from this:
{"color":[{"id":"41","name":"red"}]}
{"color":[{"id":"19","name":"blue"}]}
...
this thing by php and json_encode
{"color":[{"id":"41","name":"red"},{"id":"19","name":"blue"},...]}
Data come from DB and I use folowing code:
$json = array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow = array(
$row['color'] => array(
array(
"id" => $row['id'],
"name" => $row['name'],
)
)
);
array_push($json,$jsonRow);
}

$arr= array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow = array(
"id" => $row['id'],
"name" => $row['name'],
);
$arr[]=$jsonRow;
}
$json = json_encode(array('color'=>$arr));
echo $json;

How about this?
$json = array();
$colors= array();
while ($row = mysqli_fetch_array($getResult)) {
array_push($colors,
array(
"id" => $row['id'],
"name" => $row['name'],
)
);
$json = array( "colors" => $colors);
}

Try this:
$json = array();
$jsonRow= array();
while ($row = mysqli_fetch_array($getResult)) {
$jsonRow[] = array(
"id" => $row['id'],
"name" => $row['name'],
);
}
// color can be $row['color']
// If its constant, I am not sure if its a good idea to keep in the loop.
$json = array("color" => $jsonRow);
echo json_encode($json);

Related

PHP create json with foreach loop

I want to prepare json with php as follows. But, the services section does not occur nested. How can I get json output as below by correcting php code?
foreach($this->input->post('name') as $key => $value){
$services = [];
foreach($this->input->post('services') as $value2){
$services[] = array(
'service_name' => $value2
);
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
echo json_encode($json);
I want this:
[
{
"name":"aa",
"surname":"bb",
"birthday":"10.07.2019",
"services":[
{
"service_name":"test1",
"service_name":"test2",
},
]
},
{
"name":"cc",
"surname":"dd",
"birthday":"20.07.2019",
"services":[
{
"service_name":"test3",
"service_name":"test4",
},
]
}
]
You can try following code:
foreach($this->input->post('name') as $key => $value){
$services = [];
$count = 0;
foreach($this->input->post('services') as $value2){
$services["service".$count] = $value2;
$count++;
}
$json[] = array(
'name' => $this->input->post('name')[$key],
'surname' => $this->input->post('surname')[$key],
'birthday' => $this->input->post('birthday')[$key],
'services' => $services
);
}
$json = json_encode($json);
$json = preg_replace('/"service\d+"/', "service_name", $json);
echo $json;

How to add an array to a nested array

My PHP Code is the following, I need some assistance please:
//DB connection
$result = mysqli_query($con,"SELECT * FROM `clients`");
$info = array();
$count = 0;
$meta = array('page' => 1, 'pages' => 1, 'perpage' => -1, 'total' => 14, 'sort' => "asc", 'field' => "ID");
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$info[$row['clientid']]['id'] = $row['id'];
$info[$row['clientid']]['name'] = $row['name'];
$info[$row['clientid']]['email'] = $row['email'];
$info[$row['clientid']]['cell'] = $row['cell'];
$count++;
}
$data = json_encode(array_values($info));
echo $data;
My Result;
[{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
The JSON should add the meta array with the following result:
{"meta":
{"page": 1,"pages": 1,"perpage": -1,"total": 3,"sort": "asc","field": ID"},
"data": [{"ID":1,"name":"A","email":"a#a.com","cell":"082"},
{"ID":2,"name":"B","email":"b#b.com","cell":"083"},
{"ID":3,"name":"C","email":"c#c.com","cell":"079"}]
},
Create array of required structure and json_encode it:
$data = json_encode(array(
'meta' => $meta,
'data' => array_values($info),
));

PHP Convert single dimensional array to nested array

How do I convert an 'N' elements single dimensional array to 'N' level nested array in PHP ?
Example:
Input:
$input = array('Orange','Apple','Banana');
Expected Output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
This is my code:
$categories = array('Orange','Apple','Banana');
$count = count($categories);
for($i=0;$i<=$count;$i++){
if(isset($categories[$i+1])){
$parent = $categories[$i+1]; // parent
$categories[$i+1]=array(
'name' => $categories[$i+1],
'sub_category' => array('name' => $categories[$i])
);
}
}
$categories = $categories[$count-1];
var_dump($categories);
My code is sloppy and I also get the following incorrect output:
$output = array(
'name' => 'Banana',
'sub_category' => array(
'name' => array(
'name' => 'Apple',
'sub_category' => array(
'name' => 'Orange'
);
);
Edit 1:
The problem/solution provided here does not seem to be answering my question.
You could use simple recursion technique:
function toNestedArray(array $input, array $result = [])
{
$result = ['name' => array_pop($input)];
if (count($input)) {
$result['sub_category'] = toNestedArray($input, $result);
}
return $result;
}
$categories = array('Orange','Apple','Banana');
$count = count($categories);
$categories2=array();
for($i=$count-1;$i>0;$i--){
if($i-2>-1){
$categories2=array(
'name'=>$categories[$i],
'sub_category'=>array('name'=>$categories[$i-1],'sub_categories'=>array('name'=>$categories[$i-2]))
);
}
}
echo "<pre>";
print_r($categories2);
echo "</pre>";
A simple option is to loop over the $input array, building the $output array from inside to out.
$output = array();
foreach ($input as $name) {
if (empty($output)) {
$output = array("name" => $name);
} else {
$output = array("name" => $name, "sub_category" => $output);
}
}

Formatting json to geojson via PHP

I am trying to get some data that I have called from a mySQL database to correctly display in a GeoJSON format. Here's some of my PHP code:
$data = array(); //setting up an empty PHP array for the data to go into
if($result = mysqli_query($db,$query)) {
while ($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
}
$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$coordinates = array();
foreach($original_data as $key => $value) {
$coordinates[] = array($value['latitude'], $value['longitude']);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => array(array(
'type' => 'Feature',
'properties' => array('time' => $value['time']),
'geometry' => array('type' => 'Point', 'coordinates' => $coordinates),
),
),
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);
I've managed to get my results to look like this so far:
But I need them to look like this so that every set of coordinates has its own "type" and "properties" key-value pair:
I've already found some help with this issue here, but I just can't manage to get over this last formatting hurdle...
Instead of building coordinates, you need to build features:
$data = array(); //setting up an empty PHP array for the data to go into
if($result = mysqli_query($db,$query)) {
while ($row = mysqli_fetch_assoc($result))
{
$data[] = $row;
}
}
$jsonData =json_encode($data);
$original_data = json_decode($jsonData, true);
$features = array();
foreach($original_data as $key => $value) {
$features[] = array(
'type' => 'Feature',
'properties' => array('time' => $value['time']),
'geometry' => array(
'type' => 'Point',
'coordinates' => array(
$value['latitude'],
$value['longitude'],
1
),
),
);
}
$new_data = array(
'type' => 'FeatureCollection',
'features' => $features,
);
$final_data = json_encode($new_data, JSON_PRETTY_PRINT);
print_r($final_data);

How to bring values for each ID details in the array?

I was searching for a solution for my problem.
I have the code below:
while($row = mysql_fetch_array($resultQuery)){
$response = array(
'name' => $row['name'],
'data' => $row['data']
);
$responses[] = $response;
}
echo json_encode($responses);
The code will bring this result:
[{"name":"Name001","data":"1"},
{"name":"Name001","data":"2"},
{"name":"Name001","data":"3"},
{"name":"Name002","data":"4"},
{"name":"Name002","data":"5"},
{"name":"Name002","data":"6"}]
But I would like to have the result below:
[{"name":"Name001","data":[1,2,3]},
{"name":"Name002","data":[4,5,5]}
Each "Name" has its own ID, I would like in the "while" put each id with its own data.
Thank you for your help.
1. Update:
$id_name = "xx";
while($row = mysql_fetch_array($resultQuery)){
if($id !== $row['id']){
$response = array(
'name' => $row['name'],
'data' => array($row['data'])
);
$responses[] = $response;
}
$id_name = $row['id'];
}
echo json_encode($responses);
I am trying to check the ID first and if is different will bring to me:
[{"name":"Name001","data":["1"]},{"name":"Name002","data":["4"]}]
while($row = mysql_fetch_array($resultQuery))
$tmp[$row['name']][] = $row['data'];
foreach($tmp as $key => $item)
$responses[] = array('name' => $key, 'data' => $item);
echo json_encode($responses);
result
[{"name":"Name001","data":["1","2","3"]},{"name":"Name002","data":["4","5","6"]}]
I made a test here, hope you like.
$arr = array();
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
$arr[] = array(
'name' => 'val',
'data' => array(1, 2, 3)
);
echo json_encode($arr);
Output:
[{"name":"val","data":[1,2,3]},{"name":"val","data":[1,2,3]}]

Categories