PHP create json with foreach loop - php

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;

Related

How to group the nested array based on id?

Basically I have an associative array from the database like below,
persons = [
[id=>1, name=>adam, hobbyId=>x, hobbyName=> swim],
[id=>2, name=>brian, hobbyId=>y, hobbyName=> read],
[id=>1, name=>adam, hobbyId=>z, hobbyName=> sing]
]
I want to convert it to a new style like JSON object, something like this,
new_persons = [
[id=>1, name=>adam, hobbies => [[hobbyId=>x, hobbyName=> swim],[hobbyId=>z,
hobbyName=> sing]],
[id=>2, name=>brian, hobbies => [[hobbyId=>y, hobbyName=>read]]
]
What I have tried is,
$new_persons = array();
if (count($persons) > 0) {
foreach ($persons as $item) {
$detail = array(
'id' => $item['id'],
'name' => $item['name'],
'hobbies' => [['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]]
);
if (in_array($item['id'], $newArray)) {
array_push($newArray['hobbies'], ['hobbyId'=>$item['hobbyId'],'hobbyName'=>$item['hobbyName']]);
} else {
array_push($newArray, $detail);
}
}
}
But it doesn't meet my requirements, What is wrong with my code?
$t2 = [];
foreach ($t as $item) {
if (!isset($t2[$item['id']])) {
$t2[$item['id']] = [
'id' => $item['id'],
'name' => $item['name'],
];
}
$t2[$item['id']]['hobbies'][] = [
'hobbyId' => $item['hobbyId'],
'hobbyName' => $item['hobbyName'],
];
}

PHP remove array if subarray empty

my array image just like this, if subarray "name" is empty or null i want delete array, how to do that ?
here my current script
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
unset($data[0]); //delete first row
$data = array_values($data);
//loop search data
var_dump ($data);
die();
Assume that you have the following data set,
$array = [
[
'name' => 'not null', 'phone' => 12546
],[
'name' => '', 'phone' => 852147
],[
'name' => null, 'phone' => 96325874
],[
'name' => 'have value', 'phone' => 12546
],
];
You can filter the nulled or empty values like several ways :
1-
foreach ($array as $key => &$value) {
if (empty($value['name']) || is_null($value['name'])) {
$value = null;
}
}
$array = array_filter($array);
2-
$newData = [];
foreach ($array as $key => $value) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
}
3- using array_walk
$newData = [];
array_walk($array, function ($value, $key) use (&$newData) {
if (!empty($value['name']) && !is_null($value['name'])) {
$newData[] = $value;
}
});
4- using array_filter
$newData = array_filter($array, function ($value) {
if (!empty($value['name']) && !is_null($value['name'])) {
return $value;
}
});
<?php
$data = array();
$fixedData = array();
$countyName = array();
$numrow = 2;
echo "<pre>";
// insert to tb participant => 1
foreach($sheet as $key => $row){
if($this->split_name($row['B'])!=='' && $this->split_name($row['B'])!==NULL){
$data[] = array(
'name' => $this->split_name($row['B']),
'phone' => $row['D'],
'mobile' => $row['E'],
'institution' => $row['F'],
'departement' => $row['G'],
'address' => $row['H'],
'country' => $row['I'],
);
$numrow++;
}
}
//loop search data
var_dump ($data);
die();
I simple put an if condition inside your loop so you can check if your value is null or empty and if it is then you don't fill your new array. Also moved your counter inside the if so you increment it only in a success array push
A more "elegant" way for your if condition is this as well:
if (!empty($this->split_name($row['B'])) && !is_null($this->split_name($row['B'])))

PHP - How to create such array?

The question is simple, I want to create the array below dynamically, but the code I got now only outputs the last row. Is there anybody who knows what is wrong with my dynamically array creation?
$workingArray = [];
$workingArray =
[
0 =>
[
'id' => 1,
'name' => 'Name1',
],
1 =>
[
'id' => 2,
'name' => 'Name2',
]
];
echo json_encode($workingArray);
/* My not working array */
$i = 0;
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
$i++;
}
}
echo json_encode($dynamicArray);
You dont need to have the $i stuff that is adding another level to your array that you dont want.
$code = $_POST['code'];
$dynamicArray = [];
foreach ($Optionsclass->get_options() as $key => $value)
{
if ($value['id'] == $code)
{
$dynamicArray[] = ['id' => $key, 'name' => $value['options'];
}
}
echo json_encode($dynamicArray);
You are creating a new dynamic array at each iteration:
$dynamicArray =
[
$i =>
[
'id' => $key,
'name' => $value['options']
]
];
Instead, declare $dynamicArray = []; above the foreach, and then use:
array_push($dynamicArray, [ 'id' => $key, 'name' => $value['options']);
inside the array.

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]}]

Need to merge many rows in one JSON

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

Categories