fetching multiple rows and display in json - php

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

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;

Struggling to convert to json string

I've got a textbox that the user can enter details into it in a csv format. So they would enter something like
user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com
The out put of that when I dd(request('users')) is this
user 1, user1#email.com\n
user 2, user2#email.com\n
user 3, user3#email.com
What I would like is to save it in a json format so that it can end up looking like this
[
{
"name": "user 1",
"email": "user1#email.com"
},
{
"name": "user 2",
"email": "user2#email.com"
},
{
"name": "user 3",
"email": "user3#email.com"
}
]
I'm struggling to get it to be like how I would like it. I've tried json_encode(request('users')) but I ended up with
""user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com""
I also tried this
$replace = preg_replace('/\n+/', "\n", trim(request('users')));
$split = explode("\n",$replace);
$json = json_encode($split);
but I got this
"["user 1, user1#email.com","user 2, user2#email.com", "user 3, user3#email.com"]"
The keys name and email you want in your result are not going to appear out of thin air, you need to create them.
Split the data into individual lines, loop over those lines.
Split each line into its two parts.
Create the necessary data structure, introduce the keys you want the data to be stored under at this point.
Encode the whole thing as JSON.
$data = 'user 1,user1#email.com
user 2,user2#email.com
user 3,user3#email.com';
$lines = explode("\n", $data);
$result = [];
foreach($lines as $line) {
$parts = explode(',', $line);
$result[] = ['name' => $parts[0], 'email' => $parts[1]];
}
echo json_encode($result);
You can simply use array_map to map each line to a key-value pair created by using array_combine:
$array = array_map(function($line) {
return array_combine(['name', 'email'], str_getcsv($line));
}, explode("\n", $request('users')));
$json = json_encode($array);
var_dump($json);
The result would be:
string(133) "[{"name":"user 1","email":"user1#email.com"},{"name":"user 2","email":"user2#email.com"},{"name":"user 3","email":"user3#email.com"}]"
Try this
$xx = "user 1, user1#email.com\nuser 2, user2#email.com\nuser 3, user3#email.com";
$xxx = explode("\n",$xx);
$res = [];
foreach($xxx as $y)
{
$new = explode(',',$y);
$res[] = [
'name' => $new[0],
'email' => $new[1]
];
}
echo json_encode($res,true);
Output will be
[
{
"name":"user 1","email":" user1#email.com"
},
{
"name":"user 2","email":" user2#email.com"
},
{
"name":"user 3","email":" user3#email.com"
}
]
Try this
$data = explode("\n", trim(request('users')));
$result = collect($data)->map(function ($row) {
$columns = explode(',', $row);
return [
'name' => $columns[0] ?? null,
'email' => $columns[1] ?? null
];
});

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;

Create an object and add it to json to save a file

I have a .json file and I want to append an object to a vector in the file, but I got some errors.
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
And when I try to save it then It is saved, but without the modifications, without the new object, but where I echo $myJSON there the object seems good.
Here is an example of my .json file:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
I have been inspired from here: https://www.w3schools.com/js/js_json_php.asp and here http://www.kodecrash.com/javascript/read-write-json-file-using-php/.
What have I done wrong here? How can I resolve it? What is the correct version in this case? Thanks for any help!
Firstly, you've got your arguments to array_push() back to front. The array you want to insert into has to be the first argument you give to the function.
Secondly, you're appending a JSON string ($myJSON) to the array, instead of your object data. This doesn't work because when you later come to encode the whole array as JSON, the bit that's already a JSON string is simply treated as a string, and ends up being double-encoded. You need to push the actual PHP object to the array. It will be encoded later when everything else is.
So
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
can become simply
array_push($jsonarray['packages'], $myObj);
P.S. You can also remove the warning about "Creating default object from empty value" by writing
$myObj = new \stdClass();
just before the line
$myObj->short = $_POST["short"];
so that you're adding your properties to an object which already exists.

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