PHP JSON Encoding within foreach loop - php

I'm trying to generate the following JSON data:
[
{
"ID": "A1000",
"name": "John Simpson",
"serialID": "S41234",
"tagID": "ABC6456"
},
{
"ID": "B2000",
"name": "Sally Smith",
"serialID": "B5134536",
"tagID": "KJJ451345"
},
{
"ID": "A9854",
"name": "Henry Jones",
"serialID": "KY4239582309",
"tagID": "HYG452435"
}
]
from within a PHP foreach loop which looks like this:
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
}
I've tried using:
$arr = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID);
which works for each record within the loop, but can't work out the syntax to join them together into a single JSON data string?

Problem:- Your are over-writing your $arr variable each-time inside foreach() loop.That cause the issue.
Solution:- Instead of over-writing, assign values to array like below:-
$arr = []; //create empty array
foreach($records as $record) {
$arr[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);//assign each sub-array to the newly created array
}
echo json_encode($arr);

Add records to some kind of aggregation array and then json_encode it:
$items = [];
foreach($records as $record) {
$items[] = [
'ID' => $record->getField('propertyID'),
'name' = $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}
echo json_encode($items);

Try this:
$data= array();
foreach($records as $record) {
$data[] = array(
'ID' => $record->getField('propertyID');
'name' => $record->getField('assignedName');
'serialID' => $record->getField('serial');
'tagID' => $record->getField('tag')
);
}
echo json_encode($data);
Explanation: Make an array, put all the values on one of their numerical index with in the loop, json_enccode() it.

<?php
$ArrayName = array();
foreach($records as $record) {
$ID = $record->getField('propertyID');
$name = $record->getField('assignedName');
$serialID = $record->getField('serial');
$tagID = $record->getField('tag');
$ArrayName[] = array('ID' => $ID, 'name' => $name, 'serialID' => $serialID, 'tagID' => $tagID); //assign each sub-array to the newly created array
}
echo json_encode($ArrayName);
?
> Blockquote

You could use something like array_map() for this:
$result = array_map(function ($record) {
return [
'ID' => $record->getField('propertyID'),
'name' => $record->getField('assignedName'),
'serialID' => $record->getField('serial'),
'tagID' => $record->getField('tag'),
];
}, $records);
echo json_encode($result);

this code will help you:
<?php
$resultArray = array();
foreach($records as $record)
{
$newResultArrayItem = array();
$newResultArrayItem['ID'] = $record->getField('propertyID');
$newResultArrayItem['name'] = $record->getField('assignedName');
$newResultArrayItem['serialID'] = $record->getField('serial');
$newResultArrayItem['tagID'] = $record->getField('tag');
$resultArray[] = $newResultArrayItem;
}
$encodedArray = json_encode($ArrayName);
echo $encodedArray;
?>

Related

How to form Json array from sql pdo data in php?

The code that I have does not display what I need, tell me what I'm doing wrong
$new_array =[];
foreach($result as $row)
{
$array =[
'id'=> $row["id"],
'summ' => $row["summ"],
];
foreach($array AS $key => $val) {
$new_array[] = $val;
}
}
echo json_encode($new_array);
Outputs the following result
["26","180","25","35","24","50","23","50","22","100"]
But I need the result to be different, and I can't.
Here's an example of how it should be:
[
{"26","180"},
{"25","35"},
{"24","50"},
{"23","50"},
{"22","100"}
]
Please tell me how to achieve this?
check this :
foreach($result as $row)
$array[] = ['id'=>$row["id"], 'summ'=>$row["summ"]];
echo json_encode($array);
for example if your $result contains such a array :
$result = [['id'=>1, 'summ'=>2] , ['id'=>3, 'summ'=>4] , ['id'=>5, 'summ'=>6]];
the scripts output will be :
[
{"id":1,"summ":2},
{"id":3,"summ":4},
{"id":5,"summ":6}
]
You can skip the inner loop:
$new_array = [];
foreach($result as $row)
{
$new_array[] = [
$row['id'],
$row['summ']
];
}
echo json_encode($new_array);
That should give you the result:
[
["26","180"],
["25","35"],
...
]
Beside other answer,
I usually use array_map for this kind of array transformation.
$result = [['id' => 1, 'summ' => 2], ['id' => 3, 'summ' => 4], ['id' => 5, 'summ' => 6]];
$output = array_map(function ($item) {
return [$item['id'], $item['summ']];
}, $result);

json encode missing the comma?

I'm trying to get the correct json output after using php nested array and somehow when I use the json_encode it misses the commas between each key value pair and array of item.
$don_info_arr = array();
$don_info_arr['don_info']= array();
$st_contacts_arr = array();
$st_contacts_arr['st_contacts']= array();
$don_contact_arr = array();
$don_contact_arr['don_contact']= array();
$don_contact_item =array(
'first_name' => $donor->first_name,
'last_name' => $donor->last_name
);
//correspondence_contact
$correspondence_contact_arr = array();
$correspondence_contact_arr['correspondence_contact']= array();
$correspondence_contact_item =array(
'first_name' => $donor->first_name_c,
'last_name' => $donor->last_name_c
);
$submission = array(
"don_info" => array (
"st_contacts" => array (
"don_contact" => $don_contact_item,
"correspondence_contact" =>$correspondence_contact_item)
)));
echo json_encode($submission);
getting this result now.
{
"don_info": {
"st_contacts": {
"don_contact": {
"first_name": "Test1"
"last_name": "Test1"
}
"correspondence_contact": {
"first_name": "ABC"
"last_name": "ACDD"
}
}
}
What I want:
{
"don_info":{
"st_contacts":{
"don_contact":{
"first_name":"Test1",
"last_name":"Test2"
},
"correspondence_contact":{
"first_name":"ABC",
"last_name":"ACDD"
}
}
}

create multidimensional json array from a json in php

I have a json data. Now I want to reform it. In my json data there is a property like person_on_zone I want to make a property named person_info and store them which person under this area.
Here is my data any code. Thanks in advance
My json data
$val = [
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p1'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p2'
},
{
'city':'xx',
'zone':'yy',
'person_on_zone':'p3'
},
{
'city':'xx',
'zone':'ww',
'person_on_zone':'p1'
},
]
My expectation is
[
{
'city':'xx',
'zone':'yy',
'person_info':{
'person_on_zone':'p1',
'person_on_zone':'p2',
'person_on_zone':'p3',
}
},
{
'city':'xx',
'zone':'ww',
'person_info':{
'person_on_zone':'p1'
}
},
]
Here I tried
foreach ($val as $v) {
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2) {
$new_array['person_info'] = $v['person_on_zone'];
}
}
json_encode($new_array);
Try this, use $map to store key city-zone, then transform to array to get the result
<?php
$val = [
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p1'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p2'
],
[
'city' => 'xx',
'zone' => 'yy',
'person_on_zone' => 'p3'
],
[
'city' => 'xx',
'zone' => 'ww',
'person_on_zone' => 'p1'
]
];
$map = [];
foreach ($val as $v) {
$key = $v['city'] . $v['zone'];
if (!isset($map[$key])) {
$map[$key] = [
'city' => $v['city'],
'zone' => $v['zone'],
'person_info' => []
];
}
$map[$key]['person_info'][] = $v['person_on_zone'];
}
print_r(array_values($map));
Correct Code
foreach ($val as $v){
$new_array['city'] = $v['city'];
$new_array['zone'] = $v['zone'];
foreach ($val as $v2){
$new_array['person_info'] = $v2['person_on_zone'];
}
}
json_encode($new_array);
try this:
first decode json array then use foreach loop with key
$val = json_decode($val);
foreach ($val as $v){
$new_array['city'] = $v->city;
$new_array['zone'] = $v->zone;
foreach ($val as $key=>$v2){
$new_array[$key]['person_info'] = $v->person_on_zone;
}
}
print_r($new_array);
I think you make a mistake around composing the json. I tried with your code and i found following is the correct way to do.. Remember single quote(') is not valid in json string that is being used to define key value pair in php
// I think your code has json string and i convert it into array of objects(stdClass)
// and if your code has array then keep you code intact but need to change the notation of
// objects to associative array.
// first thing first decode json string
$values = json_decode('[
{ "city":"xx",
"zone":"yy",
"person_on_zone":"p1"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p2"
},
{
"city":"xx",
"zone":"yy",
"person_on_zone":"p3"
},
{
"city":"xx",
"zone":"ww",
"person_on_zone":"p1"
}]');
// Now declare new values as array
$new_values = [];
// walk through each object
foreach ($values as $v){
// $v becomes an object of stdClass here
// $data is a temporary array
$data['city'] = $v->city;
$data['zone'] = $v->zone;
$data['person_info'] = [];
foreach ($values as $v2){
if(!in_array($data['person_info'],['person_on_zone' => $v2->person_on_zone]))
{
// compare if zones are same or not
if($v->zone == $v2->zone)
{
// push to the array instead of assiging
array_push($data['person_info'], ['person_on_zone' => $v2->person_on_zone]);
}
}
}
// make array unique
$data['person_info'] = array_map("unserialize", array_unique(array_map("serialize", $data['person_info'])));
array_push($new_values, $data);
}
// make array unique in mutidimensional array
$new_values = array_map("unserialize", array_unique(array_map("serialize", $new_values)));
echo '<pre>';
print_r($new_values);
echo '</pre>';
One simple foreach would do,
$result = [];
foreach ($arr as $key => $value) {
//created unique combination of city and zone as key
$result[$value['city'] . $value['zone']]['city'] = $value['city'];
$result[$value['city'] . $value['zone']]['zone'] = $value['zone'];
$result[$value['city'] . $value['zone']]['person_info'][] = ['person_on_zone' => $value['person_on_zone']];
}
echo json_encode(array_values($result));die;
array_values — Return all the values of an array
Working demo.

PHP How to add all array elements to another array

I would like to add all array elements to another array as elements
Here is my codes
<pre>
$resultBasedBuild = array();
$data = {0.225, 0.132, 0.114};
$index = 0;
foreach ($data as $singleData) {
$resultBasedData[] = array(
'name' => 'my name'
,'data' => array(array($index, $singleData))
);
}
$result = json_encode($resultBasedData);
</pre>
The expected output would be
[{"name":"20140722.1304","data":[[0,0.225],[0,0.132],[0,0.114]]}]
Thank you for your help.
I sorted this problem using one more array.
$data = [0.225, 0.132, 0.114];
$result = json_encode(['name' => 'my name', 'data' => array_map(function ($item)
{
return [0, $item];
}, $data)]);

Dynamic array key in while loop

I'm trying to get this working:
I have an array that gets "deeper" every loop. I need to add a new array to the deepest "children" key there is.
while($row = mysql_fetch_assoc($res)) {
array_push($json["children"],
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
}
So, in a loop it would be:
array_push($json["children"] ...
array_push($json["children"][0]["children"] ...
array_push($json["children"][0]["children"][0]["children"] ...
... and so on. Any idea on how to get the key-selector dynamic like this?
$selector = "[children][0][children][0][children]";
array_push($json$selector);
$json = array();
$x = $json['children'];
while($row = mysql_fetch_assoc($res)) {
array_push($x,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$x = $x[0]['children'];
}
print_r( $json );
Hmmm - maybe better to assign by reference:
$children =& $json["children"];
while($row = mysql_fetch_assoc($res)) {
array_push($children,
array(
"id" => "$x",
"name" => "Start",
"children" => array()
)
);
$children =& $children[0]['children'];
}
$json = array();
$rows = range('a', 'c');
foreach (array_reverse($rows) as $x) {
$json = array('id' => $x, 'name' => 'start', 'children' => array($json));
}
print_r($json);
If you want to read an array via a string path, split the string in indices, and then you can do something like this to get the value
function f($arr, $indices) {
foreach ($indices as $key) {
if (!isset($arr[$key])) {
return null;
}
$arr = $arr[$key];
}
return $arr;
}

Categories