How to Group Json Output in Laravel 5.4? - php

is it possible to group/rearrange JSON output from laravel ? i want to group it before it send to view by system, so i need it to be done in server side not client side.
Lets said i have JSON structured like this :
id, name, date
or in example, is like this :
[[
{"id" : "1", "name" : "A", "date" : "2017-01-01"},
{"id" : "2", "name" : "B", "date" : "2017-01-01"},
{"id" : "3", "name" : "C", "date" : "2017-01-01"},
{"id" : "4", "name" : "D", "date" : "2018-01-01"},
{"id" : "5", "name" : "E", "date" : "2018-01-01"},
]]
is it possible to group it to be something like this ?
[
{"2017-01-01":[
{"id":"1","name":"A"},
{"id":"2","name":"B"},
{"id":"3","name":"C"}
]},
{"2018-01-01":[
{"id":"4","name":"D"},
{"id":"5","name":"E"},
]},
]
(In case you need to look my JSON Controller) This is my JSON Controller :
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get();
return response()->json([$harga],200);
}
Thanks !

use groupBy on your query:
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get()->groupBy(column_name_you_want_to_group_by);
return response()->json([$harga],200);
}

You can use groupBy method to do it:
return response()->json($harga->groupBy('date'), 200);

In Controller it is possible to do that as below
js = "your json";
$jsArray = json_decode($js, true);
$jsArray = $jsArray[0];
$newJsArr = [];
foreach ($jsArray as $j) {
$newJsArr[$j['date']][] = ["id" => $j['id'], "name" => $j['name']];
}
$newJsArr = json_encode([$newJsArr]);

Related

Reading data from an array with json

In a php script I have the following
$jsonurlpers = "https://api.openarch.nl/1.1/records/show.json?archive=nha&identifier=8554bfba-9fd9-4ca2-876c-feb7da095d6c";
$jsondatapers = file_get_contents($jsonurlpers);
That string I want to decode with the next command
$jsonpers = json_decode($jsondatapers ,true)[0];
But somewhere it did not work...
When I go to to the #jsonulpers I see :
Event
EventType "Overlijden"
EventDate
Year "1901"
Month "7"
Day "7"
EventPlace
Place "Egmond-Binnen"
RelationEP
Can some one tell me how I can read the value behind EventType in a variable? I tried different options but none works...
Thanks,
Fred
I did try this
e.g.
$itemevent = $jsonpers['Event'];
$itemeventtype = $itemevent['EventType']);
abs I thought
$itemeventtype would have a value of "Overlijden", but it was empty
The (json-)output from the url you gave looks like this:
{
"Event" : {
"EventType" : "Overlijden",
"EventDate" : {
"Month" : "7",
"Day" : "7",
"Year" : "1901"
},
"EventPlace" : {
"Place" : "Egmond-Binnen"
}
},
"RelationEP" : [
{
"RelationType" : "Overledene",
"EventKeyRef" : "Event1",
"PersonKeyRef" : "Person1"
},
{
"PersonKeyRef" : "Person2",
"RelationType" : "Vader",
"EventKeyRef" : "Event1"
},
{
"PersonKeyRef" : "Person3",
"RelationType" : "Moeder",
"EventKeyRef" : "Event1"
}
],
"Source" : {
"SourcePlace" : {
"Place" : "Egmond-Binnen / Egmond-Binnen"
},
"SourceAvailableScans" : {
"Scan" : {
"Uri" : "https://nha.blob.core.windows.net/scans/BS%20Overlijden/Egmond-Binnen/1901/RNH_O_EGB_1901_006-a.jpg",
"OrderSequenceNumber" : "1"
}
},
"SourceLastChangeDate" : "2015-07-31",
"SourceRemark" : {
"Value" : "Datadump ExportBS+Overlijden_20210302_102010.csv van NHA via e-mail"
},
"SourceReference" : {
"InstitutionName" : "Noord-Hollands Archief",
"DocumentNumber" : "14",
"Place" : "Haarlem"
},
"RecordGUID" : "{8554bfba-9fd9-4ca2-876c-feb7da095d6c}",
"SourceIndexDate" : {
"To" : "1901-12-31",
"From" : "1901-01-01"
},
"SourceDate" : {
"Year" : "1901",
"Month" : "7",
"Day" : "8"
},
"SourceType" : "BS Overlijden"
},
"Person" : [
{
"BirthPlace" : {
"Place" : "Egmond-Binnen"
},
"PersonName" : {
"PersonNameLastName" : "Baltus",
"PersonNameFirstName" : "Aafje"
},
"Gender" : "Vrouw",
"Age" : {
"PersonAgeYears" : "8 maanden"
}
},
{
"PersonName" : {
"PersonNameFirstName" : "Jan",
"PersonNameLastName" : "Baltus"
}
},
{
"PersonName" : {
"PersonNameLastName" : "Kuijper",
"PersonNameFirstName" : "Grietje"
}
}
]
}
After "Person":, you see a [, which means there is an array of Persons.
The first person does have a "BirthPlace", for the other persons it seems to be unknown what the "BirthPlace" is, because it is not mentioned in the json.
print($jsonpers["Person"][0]["PersonName"]["PersonFirstName"] should be: "Aafje"
and
print($jsonpers["Person"][2]["PersonName"]["PersonFirstName"] should be: "Grietje"

Yii2's mongodb collection - get all content of nested arrays

I have a Yii2 mongodb's collection that looks like this:
{
"_id" : "123",
"books" : [
{
"author" : "John",
"title" : "The Book"
},
{
"author" : "Smith",
"title" : "Something!"
}
]
}
{
"_id" : "321",
"books" : [
{
"author" : "John",
"title" : "The Book"
}
]
}
...
And I want to get an array of all books (an array of arrays basically):
[
{
"author" : "John",
"title" : "The Book"
},
{
"author" : "Smith",
"title" : "Something!"
},
{
"author" : "John",
"title" : "The Book"
}
...
]
I saw answers to close questions, but they all achieve something a bit different.
Also tried $collection->distinct('books', [], []) and it worked, but it removed duplicates which is unacceptable.
Use this MongoDB query to get this resultset
db.collection.aggregate([
{ $unwind : "$books"},
{ $group: {
_id: null,
items:
{ $push: "$books" }
}}
]);
Let's try like this way using foreach()?
<?php
$json = '[{"_id":"123","books":[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"}]},{"_id":"321","books":[{"author":"John","title":"The Book"}]}]';
$array = json_decode($json, 1);
$ids = [];
foreach($array as $v) {
foreach($v['books'] as $book){
$books[] = $book;
}
}
echo json_encode($books);
?>
Output:
[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"},{"author":"John","title":"The Book"}]
DEMO: https://3v4l.org/hdJ8H

Find a document with Doctrine ODM with equals condition on nested array of objects

I got this kind of document:
{
"_id" : ObjectId("54ad5c3b9a703a3c088b4567"),
"hard" : 750,
"coordinates" : {
"x" : 0.2388169910939489,
"y" : 0.7996551291084174
},
"indicator" : 500,
"networkIdList" : {
"networkIdData" : [
{
"networkId" : "abc123",
"type" : "SomeNetwork"
},
{
"networkId" : "123asdf",
"type" : "AnotherNetWork"
},
{
"networkId" : "abc123",
"type" : "OneMoreNetwork"
}
]
}
}
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork".
I have tried With this instruction:
$this->documentManager->createQueryBuilder('Mydocument') ->field('networkIdList.networkIdData.$.networkGamingId')->equals('abc123') ->field('networkIdList.networkIdData.$.type')->equals('')
->getQuery()
->execute());
But the cursor return no data.
I also try with
->where("function() {return this.networkIdList.networkIdData.$.networkGamingId == 'abc123'}")
but in this case i got an error that says the Object $ has no propierties.
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork"
$qb = $dm->createQueryBuilder('Foo')
->field('networkIdList.networkIdData.networkId')->equals('abc123')
->field('networkIdList.networkIdData.type')->equals('SomeNetwork');

Json decode in php basics

I'm trying to learn json in php. Here's my json result from a ElasticSearch query.
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : null,
"hits" : [ {
"_index" : "xenforo",
"_type" : "post",
"_id" : "1816069",
"_score" : null,
"sort" : [ 1365037907 ]
} ]
}
}
I assume that my php code will look something like this:
$myData = json_decode($result);
foreach($myData->hits as $var) {
$post_id[] = $var->_id;
}
Been looking for the answer for hours, I sure do appreciate any help. Thank you.
Edit: Here is the answer:
foreach($myData->hits->hits as $var) {
$post_id[] = $var->_id;
}
You're one ->hits short if you look at your JSON structure...
{
"hits" : {
"hits" : [ {
"_id" : "1816069",
$myData = json_decode($result);
foreach($myData->hits->hits as $hit) {
$post_id[] = $hit->_id;
}

Parsing JSON results

I understand how to parse json with PHP, however I don't understand how to read it with the eye. Can someone please help me understanad this?
Here is my code
<?php
$json = file_get_contents('json.txt');
$json_output = json_decode($json);
foreach ( $json_output->query as $stf )
{
echo "{$stf->response->domains->name}\n";
}
?>
Here is a sample of the json result
{ "query" : { "host" : "test.com",
"tool" : "pro"
},
"response" : { "domain_count" : "13",
"domains" : [ { "last_resolved" : "2012-01-11",
"name" : "test1.com"
},
{ "last_resolved" : "2012-01-11",
"name" : "test2.com"
},
As you can see I tried query->response->domains->name and it didn't work.
How would I tried name?
Thank you in advance
query->response->domains is an indexed array, so you need to get an index, say [0], and then get the ->name from that.
echo $stf->response->domains[0]->name."\n";
foreach ( $json_output->query->response->domains as $domain )
{
echo $domain->name;
}
Study this http://json.org/
If you're trying to read it by eye, it might help to reformat:
{
"query" : {
"host" : "test.com",
"tool" : "pro"
},
"response" : {
"domain_count" : "13",
"domains" : [{
"last_resolved" : "2012-01-11",
"name" : "test1.com"
},{
"last_resolved" : "2012-01-11",
"name" : "test2.com"
}]
}
}

Categories