create style of JSON object with PHP - php

my JSON currently looks like this
{
"customers":
[
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
},
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
]
}
and I would like it to look like this
{
"customers":
[
{
"customer":
{
"customer_id":3,
"customer_name":"Rick",
"Address":"333 North Road"
}
},
{
"customer":
{
"customer_id":4,
"customer_name":"Robby",
"Address":"444 North West Road"
}
}
]
}
It is being created in this php script but I'm unsure how to add the customer attribute to each JSON object programmtically. help please?
//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array(
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;

//populate results
$json = array();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$array = array("customer" => array( // <-- change is here
'customer_id' => $row['CustomerID'],
'customer_name' => $row['Name'],
'Address' => $row['Address']
)
);
array_push($json, $array);
foreach ($row as $r) {
}
}
$jsonstring = '{"customers":'. json_encode($json). "}";
return $jsonstring;

Related

How to group array in json php from database

I have source code like this:
elseif($postjson['aksi']=='load_Kelas'){
$data = array();
$query = mysqli_query($mysqli, "SELECT * FROM t_kelas_kuliah");
while($row = mysqli_fetch_array($query)){
$data[] = array(
'kd_kelas' => $row['kd_kelas'],
'kd_matkul' => $row['kd_matkul'],
'kd_dosen' => $row['kd_dosen'],
'waktu' => $row['waktu'],
'ruang' => $row['ruang'],
'hari' => $row['hari'],
);
}
if($query) $result = json_encode(array('success'=>true, 'result'=>$data));
else $result = json_encode(array('success'=>false));
echo $result;
}
in ionic code
async loadKelas() {
return new Promise(resolve => {
let body = {
aksi: 'load_Kelas',
};
this.accsPrvds.postData(body, 'proses_api.php').subscribe((kelas: any) => {
for (let kelaskuliah of kelas.result) {
this.datakelas.push(kelaskuliah);
}
resolve(true);
console.log(kelas);
});
});
}
result console is
result: (2) […]
​​
0: {…}
​​​
hari: "Senin" ​​​
kd_dosen: "SPK"
​kd_kelas: "A1157"
​​​kd_matkul: "IFKK1051"
​​​ruang: "B310"
​​​waktu: "09.30 - 12.00"
​​​<prototype>: Object { … }
​​1: {}
​​​hari: "Senin"
​​​kd_dosen: "SPK"
​​​kd_kelas: "A1158"
​​​kd_matkul: "IFKK1051"
​​​ruang: "B310"
​​​waktu: "12.00 - 14.30"
how to create array by category 'Hari' then I have output like this
Data = [
{
Hari : "Senin",
Kuliah = [
{ kd_dosen: "SPK", kd_kelas: "A1157", kd_matkul: "IFKK1051", ruang: "B310", waktu: "09.30 - 12.00" },
{ kd_dosen: "SPK", kd_kelas: "A1157", kd_matkul: "IFKK1051", ruang: "B310", waktu: "09.30 - 12.00" }
]}
]}
Try to replace:
elseif($postjson['aksi']=='load_Kelas'){
$data = array();
$query = mysqli_query($mysqli, "SELECT * FROM t_kelas_kuliah");
while($row = mysqli_fetch_array($query)){
$data[] = array(
'kd_kelas' => $row['kd_kelas'],
'kd_matkul' => $row['kd_matkul'],
'kd_dosen' => $row['kd_dosen'],
'waktu' => $row['waktu'],
'ruang' => $row['ruang'],
'hari' => $row['hari'],
);
}
if($query) $result = json_encode(array('success'=>true, 'result'=>$data));
else $result = json_encode(array('success'=>false));
echo $result;
}
with this:
elseif($postjson['aksi']=='load_Kelas'){
$temp = array();
$data = array();
$query = mysqli_query($mysqli, "SELECT * FROM t_kelas_kuliah");
while($row = mysqli_fetch_array($query)){
$temp[$row['hari']][] = array(
'kd_kelas' => $row['kd_kelas'],
'kd_matkul' => $row['kd_matkul'],
'kd_dosen' => $row['kd_dosen'],
'waktu' => $row['waktu'],
'ruang' => $row['ruang'],
'hari' => $row['hari'],
);
};
foreach($temp as $key => $val){
$data[] = array(
"Hari" => $key,
"Kuliah" => $val
);
};
if($query) $result = json_encode(array('success'=>true, 'result'=>$data));
else $result = json_encode(array('success'=>false));
echo $result;
}

how to change the format of json value data in codeigniter

I am trying to display data for a plugin with a predefined json format, but after I try the data does not match the format how the problem?
JSON Required
[
{
latLng: [-6.17343444,1206.834234294],
name: 'XY'
},
{
latLng: [-6.1742343244,106.898987294],
name: 'XK'
}
]
Result my JSON
[
{
"latLng": "-6.17343444,1206.834234294",
"name": "XK"
},
{
"latLng": "-6.1742343244,106.898987294",
"name": "XY"
}
]
myscript PHP
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => $row->lat_long,
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
call JSON
$.parseJSON('<?php echo base_url().'mycontrollers';?>', function(datas) {
console.log(datas);
});
You can use explode() to transform the string "-6.17343444,1206.834234294" into an array [-6.17343444,1206.834234294]:
public function lat_lang() {
foreach($this->model->name_model() as $row){
$data[] = array(
'latLng' => explode(',',$row->lat_long),
'name' => $row->city
);
}
header('content-type: application/json');
echo json_encode($data);
}
If you want to get floats (for all value in the JSON), you could use JSON_NUMERIC_CHECK:
json_encode($data, JSON_NUMERIC_CHECK);
Or, just for a specific value:
$latLng = explode(',', $row->lat_long);
$latLng = array_map('floatval', $latLng);
$data[] = array(
'latLng' => $latLng,
'name' => $row->city
);

PHP JSON Encoding within foreach loop

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

How to get join table data and pass inside array in php

I have two tables order and orderDetail. i have multiple delivery address in order detail table based on id of order table
i want to display id from order table and deliveryAddress from order detail table.i am getting below output when i print..
but unable to display delivery_address.please anyone can suggest how i display delivery_address..
{
"responseData": {
"status": 1,
"message": "",
"result": [
{
"Order": {
"id": "677",
"detail_location_instructions": "Near Inox"
},
"OrderDetail": [
{
"order_id": "677",
"delivery_address": "Smart Club Gimnasio - Avenida Álvarez Thomas, Buenos Aires, Autonomous City of Buenos Aires, Argentina"
},
{
"order_id": "677",
"delivery_address": "Lower Fort Street, Dawes Point, New South Wales, Australia"
}
]
},
{
"Order": {
"id": "680"
},
"OrderDetail": []
},
{
"Order": {
"id": "684"
},
"OrderDetail": [
{
"order_id": "684",
"delivery_address": "Four Seasons - Posadas"
}
]
}
]
}
}
below is my code
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data = $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => $value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address']
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}
You have to put the deliveryAddress in array
$c = array();
foreach ($data as $key => $value) {
$myOrders = [
'Id'=>$value['Order']['id'],
'deliveryAddress'=>[]
];
foreach($value['OrderDetail'] as $address){
$myOrders['deliveryAddress'][] = $address['delivery_address'];
}
$c[] = $myOrders;
}
Hope this will help
can you trying below code.
foreach ($data as $key => $value) {
$c[] = array(
'Order' => array(
'id'=>$value['Order']['id'],
'detail_location_instructions' => $value['Order']['detail_location_instructions'],
),
'OrderDetail' => array(
'order_id'=>$value['Order']['id'],
'deliveryAddress' => $value['OrderDetail']['delivery_address'],
),
)
}
There is cases where you dont get the delivery address, in that case, you need to check if it exists first. use the Hash utility for that purpose.
I transformed the data to an array, in order for the class Hash to work.
public function getOrderlist(){
if($this->processRequest){
$err = false;
if(empty($this->requestData['id'])){
$this->responceData['message'] = "Please provide User ID";
$err = true;
}
if(!$err){
$id = trim($this->requestData['id']);
$conditions = array('Order.user_id'=>$id);
$data =(array) $this->Order->find('all',array('conditions'=>$conditions));
if(!empty($data)){
$c = array();
foreach ($data as $key => $value) {
$c[] = array(
'Id' => Hash::get($value, 'Order.id'),
'deliveryAddress' => current(Hash::extract($value, 'OrderDetail.{n}.delivery_address', array()))
);
}
}
$this->responceData['result'] = $c;
$this->responceData['status'] = 1;
}
}
}

Two queries mysql in one object json

I have two tables that I want to convert them to json like this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
but the result of my code is this:
[
{
"date":"2013-07-20",
"id":"123456",
"year":"2013",}
,{
"people":[
{
"name":"First",
"age":"60",
"city":"1"
},
{
"name":"second",
"age":"40",
"city":"2"
},
{
"name":"third",
"age":"36",
"city":"1"
}
]
}
]
the code creates a new object to the array "people" and I want that are in the same object
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2['people'] = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2['people'],$row_temp);
}
array_push($json, $json2);
echo Json_encode($json);
How I can make the array is in the same object as the table "data"?
Many thanks
I think you may try this
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
// I think, you'll get a single row, so no need to loop
$json = mysql_fetch_array($result, MYSQL_ASSOC);
$json2 = array();
while ($row = mysql_fetch_assoc($fetch)){
$json2[] = array(
'name' => $row["name"],
'age' => $row["age"],
'city' => $row["city"]
);
}
$json['people'] = $json2;
echo json_encode($json);
Result of print_r($json) should be something like this
Array
(
[date] => 2013-07-20
[year] => 2013
[id] => 123456
[people] => Array
(
[0] => Array
(
[name] => First
[age] => 60
[city] => 1
)
[1] => Array
(
[name] => second
[age] => 40
[city] => 2
)
)
)
Result of echo json_encode($json) should be
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
If you do echo json_encode(array($json)) then you will get your whole json wrapped in an array, something like this
[
{
"date" : "2013-07-20",
"year":"2013",
"id":"123456",
"people":
[
{
"name" : "First",
"age" : "60",
"city" : "1"
},
{
"name" : "second",
"age" : "40",
"city" : "2"
}
]
}
]
You were very close, but you want the People array to be a direct value of the outer array and you've wrapped it in an extra array.
Also, please note that the MySQL library you are using is deprecated. That means it will be removed from PHP in a future release. You should replace calls from the MySQL_* family of functions with either mysqli or pdo
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
$json['people'] = array();
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json['people'],$row_temp);
}
echo Json_encode($json);
You can make it work by waiting to use the key people until the very end when you join the two arrays. Up until then, just load the data into $json and $json2.
$json = array('date' => '2013', 'id' => '123456', 'year' => '2013');
$result = mysql_query("SELECT * FROM data where id='123456'");
$fetch = mysql_query("SELECT name,age,city FROM people where id='123456'");
$json = array();
$json2 = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$json[] = $row;
}
while ($row = mysql_fetch_assoc($fetch)){
$row_temp["name"]=$row["name"];
$row_temp["age"] = $row["age"];
$row_temp["city"] = $row["city"];
array_push($json2, $row_temp);
}
$json['people'] = $json2;
echo Json_encode($json);

Categories