Creating custom JSON layout in PHP [duplicate] - php

This question already has answers here:
Create JSON object using PHP [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to create JSON in a PHP variable that represents the following JSON structure:
{
"nodes": [
{"id": "example#email.com", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "example#email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.
The code I currently have is:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example#email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example#email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
However when I view the output in JSON format there are some issues:
{
"nodes": ["\"id\": \"example#email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"example#email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.

It is better using json_encode, note that you should use arrays all the way:
$entityarray['nodes'][] = array( 'id' => 'example#email.com'
, 'group' => 1
);

Try this
$result = array();
$nodes_array = array();
$temp = array();
$temp["id"] = "example#gmamil.com";
$temp["group"] = 1;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["group"] = 2;
$nodes_array[] = $temp;
$temp = array();
$temp["id"] = "Device ID 9057673495b451897d14f4b55836d35e";
$temp["group"] = 2;
$nodes_array[] = $temp;
$links_array = array();
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c";
$temp["value"] =1;
$links_array[] = $temp;
$temp = array();
$temp["source"] = "example#email.com";
$temp["target"] = "Exact ID 9057673495b451897d14f4b55836d35e";
$temp["value"] =1;
$links_array[] = $temp;
$result["nodes"] = $nodes_array;
$result["links"] = $links_array;
echo json_encode($result);

Related

How to make multiple records in array php

From my database i am receaving array, that i`m later sending using Fetch Api to my frontend and display data that was send. It looks like this:
return $stmt->fetchAll(PDO::FETCH_NAMED);
and the given output in JSON is like this:
[
{
"name": [
" name1",
" name2",
" name3"
],
"date": "2022-02-05 12:00:00",
"round": "3",
"coordinate x": "number",
"coordinate y": "number",
"leauge_id": 4
}, etc.
What i want to do is to replace fields coordinate x, coordinate y and insert into this array new field location(based on GoogleGeocodeAPI i will transofrm coordinates into location name) and insert it into this array so i will later be able to display this location.
Here is what i tried to do:
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result['nameA'] = $match['name'][0];
$result['nameB'] = $match['name'][1];
$result['nameC'] = $match['name'][2];
$result['date'] = $match['date'];
$result['round'] = $match['round'];
$result['leauge_id'] = $match['leauge_id'];
$result['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
}
return $result;
Output from JSON:
{
"nameA": " name",
"nameB": " name",
"nameC": " name",
"date": "2022-02-05 12:00:00",
"round": "29",
"leauge_id": 6,
"location": "location"
}
But it ends up that i`m kinda overwriting the posistion and in the end i am sending only one, the last record. How can i make this work?
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
foreach ($matches as $match){
$result[] = [
'nameA' => $match['name'][0],
'nameB' => $match['name'][1],
'nameC' => $match['name'][2],
'date' => $match['date'],
'round' => $match['round'],
'leauge_id' => $match['leauge_id'],
'location' => $this->reverse_geocode($match['coordinate x'],$match['coordinate y']),
];
}
return $result;
One way to do this is to create a variable $i and use that to key your array...
<?php
$matches = $stmt->fetchAll(PDO::FETCH_NAMED);
$i=0;
foreach ($matches as $match){
$result[$i]['nameA'] = $match['name'][0];
$result[$i]['nameB'] = $match['name'][1];
$result[$i]['nameC'] = $match['name'][2];
$result[$i]['date'] = $match['date'];
$result[$i]['round'] = $match['round'];
$result[$i]['leauge_id'] = $match['leauge_id'];
$result[$i]['location']= $this->reverse_geocode($match['coordinate x'],$match['coordinate y']);
$i++;
}
return $result;

How to create JSON object in php without key name?

I am trying to create JSON Object and array in php. but It creates unwanted indexes (keys).Is there any way I can create object without Key name like $temp_obj-> No Key here $all_products_array; ???? Thanks in advance
This is How am I trying...
$combo_info = new stdClass();
$combo_info-> combo_id = $combo_id;
$combo_info-> combo_name = $combo_name;
$temp_obj = new stdClass();
for($i=0; $i<=16; $i++){
$all_products_array = array();
$all_products_array = array("product_id" => $product_id,"product_name" => $product_name);
$temp_obj->all_products_array_inside[$i] = $all_products_array;
}
$myObj = new stdClass();
$myObj->combo_info = $combo_info;
$myObj->all_products_array = $temp_obj;
$myfinalobj-> myfinalobj[$i] = $myObj;
header('Content-Type: application/json');
echo '['. json_encode($myfinalobj, JSON_PRETTY_PRINT) .']';
It will produce below result where index/key named "1" and "all_products_array_inside" are unwanted. Because I have to go myfinalobl->all_products_array->all_products_array_inside[1].product_id
but i want easy like myfinalobl->all_products_array[i].product_id
Is there any way I can create object without Key name like
$temp_obj-> No Key here $all_products_array; ????
{
"myfinalobj": {
"1": {
"combo_info": {
"combo_id": "1",
"combo_name": "Supper_deal",
},
"all_products_array": {
"all_products_array_inside": {
"1": {
"product_id": "1",
"product_name": "TV"
},
"2": {
"product_id": "2",
"product_name": "Laptop"
}
}
}
}
}
}
You are creating the key yourself (from $i), so just don't do that...
$myfinalobj->myfinalobj[$i] = $myObj;
Here you have [$i] - remove it:
$myfinalobj->myfinalobj = $myObj;

fetching multiple rows and display in json

I have a PHP code like:
while ($row2 = mysqli_fetch_assoc($check2)) {
// $leadarray[] = $row2;
$service_id[$i] = $row2['service_id'];
$row1['service_id'][$i] = $service_id[$i];
$service_name[$i] = $row2['service_name'];
$row1['service_name'][$i] = $service_name[$i];
$i++;
}
$leadarray[] = $row1;
$trimmed1['leaddetails'] = str_replace('\r\n', '', $leadarray);
echo json_encode($trimmed1);
getting output like
{
"leaddetails": [
{
"service_id": [
"7",
"2"
],
"service_name": [
"Past Control Services",
"Civil Finishing"
],
}
]
}
I want output like:
"service_id": [
1: "7",
2: "2"
],
"service_name": [
1: "Past Control Services",
2: "Civil Finishing"
],
or
[
"service_id": "7",
"service_name": "Past Control Services",
"service_id": "2",
"service_name": "Civil Finishing",
]
$trimmed1 is considered an object when passing it to json_encode (associative array in PHP) because you explicitly give it a key (considered an object property in JSON):
$trimmed1 = [];
$trimmed1['leaddetails'] = 'foobar';
This will result in json_encode encoding $trimmed1 into an object:
{
"leaddetails": "foobar"
}
To get your desired result, have $trimmed1 be considered an ARRAY when passed to json_encode.
$trimmed1[] = str_replace('\r\n', '', $leadarray); // push instead of assign
second option is not posible
you can make like this
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
[{"service_id":"7", "service_name":"Past Control Services"}, {"service_id":"2", "service_name":"Civil Finishing"}]
using class for make like that
class Data{
$service_id;
$service_name;
}
$obj = new Array();
while ($row2 = mysqli_fetch_assoc($check2)){
$data = new Data();
$data->service_id = $row2['service_id'];
$data->service_name = $row2['service_name'];
array_push($obj, $data);
}
echo json_encode($obj);
Create the 2-dimensional array first. Then push onto the nested arrays during the loop.
$result = ["service_id" => [], "service_name" = []];
while ($row2 = mysqli_fetch_assoc($check2)) {
$result["service_id"][] = $row["service_id"];
$result["service_name"][] = $row["service_name"];
}
echo json_encode($result);

laravel: JSON Field Comparison with Array

laravel-5.7/mysql
In my database, I have a json format field like this:
field name: features:
[
{"id": 1, "url": null, "name": "A"},
{"id": 2, "url": null, "name": "B"}
]
Also in its model,I wrote this
protected $casts = [
'features' => 'array'
];
Now I create an array:
$features = array();
temp = array();
temp['id'] = 1;
temp['url'] = null;
temp['name'] = A;
$features[] = temp;
temp = array();
temp['id'] = 2;
temp['url'] = null;
temp['name'] = B;
$features[] = temp;
How can I compare $features array with features field in the database?
ّI checked these:
$fff = \App\Cart::whereFeatures($features)->get()->first();
or
$fff = \App\Cart::whereFeatures(json_encode($features))->get()->first();
or
$fff = \App\Cart::whereFeatures(json_encode($features,JSON_UNESCAPED_UNICODE))->get()->first();
Use a raw expression to cast the comparison value:
$fff = \App\Cart::whereRaw('features = cast(? as json)', json_encode($features))->get();

PHP JSON array from query

I'm not a php developer, but trying to get an array within an array from this query:
SELECT distinct d.DiscussionId as DiscussionId, d.AvatarId as AvatarId, d.Heading as Heading, d.body as Body, c.commentid as CommentId, c.userid as UserId, c.comment as Comment
FROM Discussion AS d
INNER JOIN Comments AS c ON d.discussionid = c.discussionid
WHERE d.DiscussionId = c.DiscussionId
The JSON output is:
[
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "1",
"UserId": "2",
"Comment": "This is a comment i made"
}
]
},
{
"DiscussionId": "1",
"AvatarId": null,
"Heading": "New discussion heading",
"Body": "This is the discussion body",
"Comments": [
{
"DiscussionId": "1",
"CommentId": "2",
"UserId": "2",
"Comment": "This is a second comment"
}
]
}
]
What I need is to nest all Comments in one Discussion.
the php code is below, no error but not giving the output i want, for each discussion there maybe several comments so i need DiscussionId:1 displayed only once with multilple comments array
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$record++;
$model[] = array();
$model[$record]['DiscussionId'] = $e['DiscussionId'];
$model[$record]['AvatarId'] = $e['AvatarId'];
$model[$record]['Heading'] = $e['Heading'];
$model[$record]['Body'] = $e['Body'];
$model[$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);
You are selecting many comments from a single dicussion.
You should overwrite that variable instead of creating a new element at each iteration:
$model = array();
while($e = mysql_fetch_assoc($result)){
//We overwrite the same variable, that's ok
$model['DiscussionId'] = $e['DiscussionId'];
$model['AvatarId'] = $e['AvatarId'];
$model['Heading'] = $e['Heading'];
$model['Body'] = $e['Body'];
//Only comments would be an array
$model['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
try it like this:
Added Disscussion Id as an index for the array, should work for you. Just off the top of my head, not tested.
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = -1;
$currentWeID = -1;
$model = array();
while($e = mysql_fetch_assoc($result)){
$record++;
$model[$e['DiscussionId']][$record]['AvatarId'] = $e['AvatarId'];
$model[$e['DiscussionId']][$record]['Heading'] = $e['Heading'];
$model[$e['DiscussionId']][$record]['Body'] = $e['Body'];
$model[$e['DiscussionId']][$record]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
);
}
print json_encode ($model);
Try this:
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$model = array();
$record = 0;
$currentWeID = -1;
while($e = mysql_fetch_assoc($result)){
$model[] = array();
$model[$record][$e['DiscussionId']]['AvatarId'] = $e['AvatarId'];
$model[$record][$e['DiscussionId']]['Heading'] = $e['Heading'];
$model[$record][$e['DiscussionId']]['Body'] = $e['Body'];
$model[$record][$e['DiscussionId']]['Comments'][] = array(
'DiscussionId'=> $e['DiscussionId'],
'CommentId' => $e['CommentId'],
'UserId' => $e['UserId'],
'Comment' => $e['Comment']
); ;
$record++;
}
print json_encode ($model);
This might help you. Dont forget to accept answer if it helps.
It's not possible with just changing the SQL query: you need to change the server-side code (PHP, as I understand) which transorms query results to JSON.

Categories