ActiveRecord get array inside array with three tables - json

I'm trying to output a json string with the ActiveRecord system in the Codeigniter framework.
The right syntax for my json string need to be:
{
"data": [
[
{
"name": "xxxx",
"city": "xxx",
"address": "xxx",
"image": "xxx",
"marketId": "1",
"products": [
"Id": "36",
"productId": "36",
"price": "120",
"discounts": "1",
"title": "xxx",
"category": "2",
"weight": "12.5",
"code": "EA123",
"isUnitized": "0",
"description": "xxxx",
"changed": "2014-04-08 15:09:16",
"units": "xxx"
]
}
]
]
Pay attention to the "products" array.
But the string that i'm getting from the code is not right, here is the wrong string:
{
"data": [
[
{
"name": "xxx",
"city": "xxx",
"address": "xx x",
"image": "xxx",
"marketId": "1",
"Id": "36",
"productId": "36",
"price": "120",
"discounts": "1",
"title": "xxx",
"category": "2",
"weight": "12.5",
"code": "EA123",
"isUnitized": "0",
"description": "xxx",
"changed": "2014-04-08 15:09:16",
"units": "xxx"
}
]
]
You can see that the product array is't showing like an array but as a regular string inside the main array.
Here is the code that have I built:
$this->db->select('*');
$this->db->from('markets');
$this->db->where("markets.marketId", $marketId);
$this->db->join('linkedPrices', 'linkedPrices.marketId = markets.marketId');
$this->db->join('products', 'products.Id = linkedPrices.productId');
$this->db->order_by("linkedPrices.price", "DESC");
$output[] = $this->db->get()->result();
So you can see here the join between the table. The goal is to show the products tables as individual array inside the markets array as you can see at the top example of the json string.

No not this way you gonna have array of products foreach your dataset it can be done by looping over your results and fetch the relevant product data
$result=new stdClass();
$this->db->select('*');
$this->db->from('markets');
$this->db->where("markets.marketId", $marketId);
$this->db->join('linkedPrices', 'linkedPrices.marketId = markets.marketId');
$this->db->order_by("linkedPrices.price", "DESC");
$result = $this->db->get()->result();
foreach($result as $r){
$result->products=$this->db->select('*')
->from('products')
->where('id',$r->productId)
->get()
->result();
}
$output[]=json_encode($result);

Related

Laravel Loop through nested array

{
"8": {
"id": "8",
"name": "Third Product",
"price": 3000,
"quantity": "1",
"attributes": {
"tax": 7.5,
"shop": "Edificeweb",
"image": "rp-4.jpg"
},
"conditions": []
},
"9": {
"id": "9",
"name": "The fourth",
"price": 200,
"quantity": "1",
"attributes": {
"tax": 7.5,
"shop": "Edificeweb",
"image": "product-2.jpg"
},
"conditions": []
}
}
I stored my cart as a json column in my order page... How do I check for authenticated user using whereJsonContains....
I tried
$Order=Order::whereJsonContains('cart->attributes->shop',Auth::user()->name)->get();
It returns empty array
If you're working with mysql you should try something like:
$Order = Order::whereJsonContains('cart->attributes', ['shop' => Auth::user()->name])->first();
With postgresql try with:
$Order = Order::whereJsonContains('cart->attributes', [['shop' => Auth::user()->name]])->first();
If it's case sensitivity you should try raw:
$Order = Order::whereJsonContains(DB::raw('lower("cart->attributes"::text)'),
[["shop" => strtolower(Auth::user()->name)]])->first();
I recommend that you save the objects without numbers as indicators, if you are saving it with numbers as indicators ("9", "8") you should try:
$Order = Order::whereJsonContains('cart->"$[*].attributes"', ['shop' => Auth::user()->name])->first();
btw, I would recommend that you use first instead of get but it would be better for you to try it and see what your convenience is ;)

Perl: Combine two JSONs

I am looking for help/guidance to combine multiple JSON into 1 JSON based on a node in PERL. For example here are the two JSON content that I want to combine.
JSON #1:
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Alpha One",
"title": "Security Chief",
"locations": [{"id": "730WLCS"}, {"id": "943MCS"}]
},
{
"name": "Alpha Two",
"title": "Security Manager"
}
]
}
JSON #2:
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Beta One",
"title": "Architect",
"locations": [{"id": "730WLCS"}]
}
]
}
RESULT JSON :
{
"title": "All",
"lastModified": "2017-04-11T00:00:00.000+0000",
"users": [{
"name": "Alpha One",
"title": "Security Chief",
"locations": [{"id": "730WLCS"}, {"id": "943MCS"}]
},
{
"name": "Alpha Two",
"title": "Security Manager"
},
{
"name": "Beta One",
"title": "Architect",
"locations": [{"id": "730WLCS"}]
}
]
}
Basically, I want to combine only the "users" node.
I tried to get the node using from_json and tried to push into an array, but it is not working.
Here is the code that I tried:
my $json_obj1 = from_json($json_txt1, {utf8 => 1});
my $json_obj2 = from_json($json_txt2, {utf8 => 1});
push(#myJSON, #{$json_obj1->{'users'}});
push(#myJSON, #{$json_obj2->{'users'}});
Any help is much appreciated.
Thank you.
my $json_obj1 = decode_json($json_txt1); # Same as from_json($json_txt1, {utf8 => 1})
my $json_obj2 = decode_json($json_txt2);
push #{ $json_obj2->{users} }, #{ $json_obj1->{users} };
If you want to remove duplicates , keeping the newer records (assuming $json_obj1 is the older state), you can use the following:
my %seen;
#{ $json_obj2->{users} } =
grep !$seen{$_->{name}}++,
#{ $json_obj2->{users} },
#{ $json_obj1->{users} };

How can I return an array of object based on matching ids?

I am trying to match the ids of two json files and return the matching objects. These are the 2 json files:
{
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
This is the second one:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
As a result of the 2 matching idvalues I should get:
[
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false,
"title": "Entertainment and stuff"
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"title": "Sport for everyone"
}
]
I was wondering if there was a fancy way using lodash or something else and do this in a nice compact way?
One possible solution would be to use merge to merge two objects that have the id as the key. This can be done using keyBy on the array and also on the values of the first object. Intersection is used find ids that are in both arrays.
let list1 = {
"een": {
"id": "100",
"title": "Entertainment and stuff"
},
"twee": {
"id": "107",
"title": "Sport for everyone"
},
"drie": {
"id": "108",
"title": "Eating is good"
}
}
let list2 = [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false
}
]
let o1 = _.keyBy(_.values(list1), 'id');
let o2 = _.keyBy(list2, 'id');
let matchingIds = _.intersection(_.keys(o1), _.keys(o2));
let result = _.chain(o1)
.pick(matchingIds)
.merge(_.pick(o2,matchingIds))
.values()
.value()
Building on #GruffBunny's answer, you want to take his result and filter out those ids that aren't found in o1 and o2.
let o1 = _.keyBy(_.values(list1), 'id'));
let o2 = _.keyBy(list2, 'id');
let idsToPull = _.difference( _.map(o1, 'id'), _.map(o2, 'id')) //["108"]
let merged = _.values(_.merge(o1, o2 ));
let result = _.filter(merged, function(obj){ return _.indexOf(idsToPull, obj.id) === -1 })

Group similar items in array of objects

Hello i have the following JSON:
[
{
"name": "Donation",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 1,
"category": "Donation",
"name": "Some Donation",
"price": 10,
"description": "Hahahaha",
"company": "Donation Company 1"
}
}
},
{
"name": "Donation",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 2,
"category": "Donation",
"name": "Another Donation",
"price": 50,
"description": "LoL",
"company": "Donation Company 1"
}
}
},
{
"name": "Insurance Company 1",
"collection": {
"name": "Hehe",
"collection": {
"id": 3,
"category": "Insurance",
"name": "Lorem Ipsum Solor",
"price": 25,
"description": "Lmao",
"company": "Insurance Company 1"
}
}
},
{
"name": "Insurance Company 2",
"collection": {
"name": "Donation Company 1",
"collection": {
"id": 5,
"category": "Insurance",
"name": "Sample Extra",
"price": 500,
"description": "Lorem ipsum dolor",
"company": "Insurance Company 2"
}
}
}
]
I'm having trouble trying to group the similar items together, as in all items in the same category appear in the same category array.
And in each category all items that have the same company end up in the same company array.
This is an example what i am trying to accomplish, i used an online editor to construct the JSON:
expected-json-output-when-saved
I used the laravel collect() helper function to construct my array of objects, i have tried several combinations in foreach loops and have been at it for hours but have still not been able to get the expected JSON returned.
Assuming you json_decode() that JSON string and stored it in a $json variable, you can do the following:
$collection = collect($json);
$collection = $collection->groupBy('collection.collection.category');
Dump the $collection variable to see the result.

insert the array into the database

I am getting this result when I am using graph api . it is in array format
{
"id": "216805086",
"name": "raj sharma",
"first_name": "raj ",
"last_name": "sharma",
"link": "https://www.facebook.com/raj.sharma.5",
"username": "raj .sharma.5",
"favorite_teams": [
{
"id": "198358615428",
"name": "Mumbai Indians"
},
{
"id": "190313434323691",
"name": "Indian Cricket Team"
}
],
"favorite_athletes": [
{
"id": "100787839962234",
"name": "Saina Nehwal"
}
],
"gender": "male",
"email": "raj.discoverme#gmail.com",
"timezone": 5.5,
"locale": "en_GB",
"verified": true,
"updated_time": "2013-08-13T06:01:17+0000"
}
I am working in a php language and phpmyadmin database . Now i want to insert the array into my database . Should i make a column for id , name , first_name ,last_name,link,favorite_teams etc or should i make a one column for all of this ........
how toinsert tha array into the database
Actually this is not an array. This is JSON. In JSON there are two formats,
JSONArray [ ]
JSONObject { }
You are getting the JSONObject as your output. There is a function in PHP callerd JSONDecode.
Go through this you will get idea.
Storing facebook app data in a database is against Facebook policy http://developers.facebook.com/policy/
$data = '{
"id": "216805086",
"name": "raj sharma",
"first_name": "raj ",
"last_name": "sharma",
"link": "https://www.facebook.com/raj.sharma.5",
"username": "raj .sharma.5",
"favorite_teams": [
{
"id": "198358615428",
"name": "Mumbai Indians"
},
{
"id": "190313434323691",
"name": "Indian Cricket Team"
}
],
"favorite_athletes": [
{
"id": "100787839962234",
"name": "Saina Nehwal"
}
],
"gender": "male",
"email": "raj.discoverme#gmail.com",
"timezone": 5.5,
"locale": "en_GB",
"verified": true,
"updated_time": "2013-08-13T06:01:17+0000"
}';
//decode to get as php variable
$values = json_decode($data,true); //true to decode as a array not an object
$sql = "INSERT INTO TableName (id,name,first_name,last_name,link,username)
VALUES ('".$values['id']."','".$values['name']."','".$values['first_name']."','".$values['last_name']."','".$values['link']."','".$values['username']."')";
mysql_query($sql);
Json_decode() takes a JSON encoded string and converts it into a PHP variable.