Rejecting certain index parameters in an array - php

Given an array, in which each index there are certain key value pairs, how do I select certain key value pairs and reject the others.
$channels = Channel::get()->toArray();
This will yield the following Array:
"channels": [
{
"id": 1,
"name": "Info Release",
"slug": "info-release",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-02 01:23:50",
"updated_at": "2018-12-05 07:54:41"
},
{
"id": 11,
"name": "Casual News",
"slug": "casual-news",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-05 05:34:50",
"updated_at": "2018-12-05 07:54:32"
},
{
"id": 12,
"name": "haha",
"slug": "haha",
"desc": "Contains blah blah.",
"access_level": "0",
"created_at": "2018-12-29 23:27:16",
"updated_at": "2018-12-29 23:27:16"
}
],
What is the best way to turn that array into this:
"channels": [
{
"id": 1,
"name": "Information Release",
"slug": "information-release",
},
{
"id": 11,
"name": "Casual News",
"slug": "casual-news",
},
{
"id": 12,
"name": "haha",
"slug": "haha",
}
],
So that if I write
$channels[0]->id
it will spit out 1

Can You try this
$viewFileds = ['id', 'name', 'slug'];
$channels = Channel::get()
->map(function ($each) use ($viewFileds) {
return Arr::only($each, $viewFileds);
});
It will return the new Collection by Only the field enabled in the $viewFileds
Hope it helps

Related

Obtain KEY Value Array in variable PHP

Hi I have this array code and I need to get: user_id": 4
I just need to get the value 4 from user_id
I have this code but it doesn't work
$myvar = $request['order'][0]['user_id'];
{
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NpdGUudGVzdC9wdWJsaWMvYXBpL2xvZ2luIiwiaWF0IjoxNjIzODExMTE1LCJuYmYiOjE2MjM4MTExMTUsImp0aSI6Ind2bExlTlJHdkdpU2xmVUYiLCJzdWIiOjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.-Q56kEsHZgVEtaMzSS9Ub11imYjWjFbJMAug3Wx7WTg",
"user": {
"success": true,
"data": {
"id": 2,
"auth_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3NpdGUudGVzdC9wdWJsaWMvYXBpL2xvZ2luIiwiaWF0IjoxNjIzODExMTE1LCJuYmYiOjE2MjM4MTExMTUsImp0aSI6Ind2bExlTlJHdkdpU2xmVUYiLCJzdWIiOjIsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.-Q56kEsHZgVEtaMzSS9Ub11imYjWjFbJMAug3Wx7WTg",
"name": "Leo",
"email": "ventas#nikostore.net",
"phone": "+51943363373",
"default_address_id": 3,
"default_address": {
"address": "mi dirección",
"house": null,
"latitude": "-1.327080900000001",
"longitude": "-10.6348053",
"tag": null
},
"delivery_pin": "51972",
"wallet_balance": 0,
"avatar": null,
"tax_number": null
},
"running_order": null,
"delivery_details": null
},
"order": [{
"selectedaddons": [{
"addon_category_name": "Comida Marina Ingredientes",
"addon_id": "2",
"addon_name": "Cangrejo Adicional",
"price": "32.00"
}],
"id": 5,
"restaurant_id": 12,
"item_category_id": 2,
"name": "Producto 1 Loquillo",
"price": "423.00",
"old_price": "0.00",
"image": "https://localhost/phpmyadmin/themes/pmahomme/img/logo_left.png",
"is_recommended": 1,
"is_popular": 1,
"is_new": 1,
"desc": "<p>321312</p>",
"placeholder_image": null,
"is_active": 1,
"is_veg": null,
"order_column": null,
"addon_categories": [{
"id": 2,
"name": "Comida Marina Ingredientes",
"type": "SINGLE",
"user_id": 4,
"created_at": "2021-06-10 20:18:37",
"updated_at": "2021-06-10 20:39:18",
"description": null,
"pivot": {
"item_id": 5,
"addon_category_id": 2
},
"addons": [{
"id": 2,
"name": "Cangrejo Adicional",
"price": "32.00",
"addon_category_id": 2,
"user_id": 4,
"created_at": "2021-06-10 20:20:30",
"updated_at": "2021-06-10 20:38:51",
"is_active": 1
}, {
"id": 3,
"name": "Pene",
"price": "95.00",
"addon_category_id": 2,
"user_id": 4,
"created_at": "2021-06-10 23:52:53",
"updated_at": "2021-06-10 23:52:53",
"is_active": 1
}]
}],
"quantity": 1
}],
"coupon": null,
"location": {
"lat": "-5.187080900000001",
"lng": "-80.6348053",
"address": "midreccion",
"house": null,
"tag": null
},
"order_comment": null,
"total": {
"productQuantity": 1,
"totalPrice": 455
},
"method": "COD",
"payment_token": "",
"delivery_type": 1,
"partial_wallet": false,
"dis": 0,
"pending_payment": false,
"tipAmount": null
}
Working from the JSON string you posted here, you need to decode it first with json_decode(). Assuming no flags are set, this will decode to a mix of objects and arrays as represented in the JSON string.
$str = '{"token": "ey...WTg",
"user": {
...
}
}'; //The JSON string you posted in the question
$request = json_decode($str);
From there the path to the user_id is:
$request->order[0]->addon_categories[0]->user_id // 4
Use foreach loop.
Assuming that you have stored array in variable $array.
Code :
foreach($array as $arr)
{
if($arr['user_id'] == 4)
{
$user = $arr;
}
}
You will get the entire object which has user_id 4, you can get related column by
$user_id = $user['user_id];
Hope this will be useful.

How to return unique values in laravel

Here I have this sample data which returns based on category products and I need to limit repeated values.
Raw JSON
[{
"brand": {
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "No Brand",
"slug": "no-brand",
"description": "null"
},
"options": [{
"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"parent_id": "null",
"name": "Need Insurance?"
},
{
"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"parent_id": "null",
"name": "Color",
"slug": "color"
}
],
"rating": [],
"tags": [{
"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f",
"name": "options",
"slug": "options",
"photo": "null"
}],
"variations": [{
"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"parent_id": "null",
"name": "Ram",
"slug": "ram",
"photo": "null"
},
{
"id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"parent_id": "null",
"name": "cpu",
"slug": "cpu",
"photo": "null"
},
{
"id": "e63ac831-f595-4889-83d2-a5be65734758",
"parent_id": "null",
"name": "Monitor",
"slug": "monitor"
}
]
},
{
"brand": {
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "No Brand",
"slug": "no-brand",
"description": null
},
"options": [{
"id": "522da418-eb3f-43e9-9392-63c941842a52",
"parent_id": null,
"name": "Color",
"slug": "color-3"
}],
"rating": [],
"tags": [],
"variations": [{
"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"parent_id": null,
"name": "cpu",
"slug": "cpu-3",
"photo": null
}]
}
]
Sample data
filters: [{,…}, {,…}]
0: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
options: [{id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…},…]
0: {id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…}
1: {id: "73298c18-4ccc-4138-afa5-71d3d00dff9b", parent_id: null, name: "Color", slug: "color",…}
rating: []
tags: [{id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…},…]
variations: [,…]
0: {id: "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", parent_id: null, name: "Ram", slug: "ram", photo: null,…}
1: {id: "e5c70766-a558-4539-b41f-77f72c819a7c", parent_id: null, name: "cpu", slug: "cpu", photo: null,…}
2: {id: "e63ac831-f595-4889-83d2-a5be65734758", parent_id: null, name: "Monitor", slug: "monitor",…}
1: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
options: [{id: "522da418-eb3f-43e9-9392-63c941842a52", parent_id: null, name: "Color", slug: "color-3",…}]
0: {id: "522da418-eb3f-43e9-9392-63c941842a52", parent_id: null, name: "Color", slug: "color-3",…}
rating: []
tags: [,…]
variations: [,…]
0: {id: "8e9a26c5-2ee4-4d86-9244-a10596d67fea", parent_id: null, name: "cpu", slug: "cpu-3", photo: null,…}
Explanation
As you can see each of my products has same fields of data and some of them are the same, for instance in options both products have Color or in variations both have cpu or brand of both is the same, in final results I need to have only 1 Color and 1 cpu and 1 brand as they are the same.
code
This is how code above returns
$data = [];
foreach($products as $i => $product) {
$data[$i]['brand'] = $product->brand;
$data[$i]['rating'] = $product->rating;
$data[$i]['variations'] = $product->variations;
$data[$i]['options'] = $product->options;
$data[$i]['tags'] = $product->tags;
}
Note: the final result is a merge of all products data into single array, but unique values. That's what I'm looking for.
Any idea?
Update
sample of final result would be something like this
finalResult: [{,…}, {,…}]
0: {,…}
brand: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…}
0: {id: "fe877b45-8620-453a-8805-63f0cbd80752", name: "No Brand", slug: "no-brand", description: null,…},…] // it was same in both products
options: [{id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…},…]
0: {id: "324af955-1aa9-42ea-be6e-bb4e5623a97a", parent_id: null, name: "Need Insurance?",…}
1: {id: "73298c18-4ccc-4138-afa5-71d3d00dff9b", parent_id: null, name: "Color", slug: "color",…} // it was same in both products
rating: []
tags: [{id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…},…]
0: {id: "8a31ee4c-3302-4357-9686-bd4308bbf39f", name: "options", slug: "options", photo: null,…}
1: {id: "94ef99b6-ed2a-4eea-9248-e4775159eb58", name: "product", slug: "product", photo: null,…}
2: {id: "378802b3-d13a-48c4-afa2-f9fed94d69ee", name: "werg", slug: "werg", photo: null, active: "yes",…} // added from another product
3: {id: "f1380f50-af59-4f6a-8eca-d40689c1c1c1", name: "werwg", slug: "werwg", photo: null, active: "yes",…} // added from another product
variations: [,…]
0: {id: "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", parent_id: null, name: "Ram", slug: "ram", photo: null,…}
1: {id: "e5c70766-a558-4539-b41f-77f72c819a7c", parent_id: null, name: "cpu", slug: "cpu", photo: null,…} // it was same in both products
2: {id: "e63ac831-f595-4889-83d2-a5be65734758", parent_id: null, name: "Monitor", slug: "monitor",…}
Update 2
Getting children of data
Options and Variations both have children (i.e Cpu => [Core i7, Core i3]) or color => ['red', 'black'] so I need to collect this children's and put them under their parents data.
Option model
public function options()
{
return $this->hasMany(Option::class);
}
public function children() {
return $this->hasMany(Option::class,'parent_id','id') ;
}
public function parent()
{
return $this->belongsTo(Option::class,'parent_id');
}
public function isParent()
{
return !$this->parent_id ? true : false; // if parent_id is null => is a Parent Option
}
Variant model
public function variants()
{
return $this->hasMany(Variant::class);
}
public function children() {
return $this->hasMany(Variant::class,'parent_id','id') ;
}
public function parent()
{
return $this->belongsTo(Variant::class,'parent_id');
}
public function isParent()
{
return !$this->parent_id ? true : false; // if parent_id is null => is a Parent Variant
}
Note: as you probably understand relationship between parent and children are defined by parent_id column.
Sample data (includes all arrays and their childs)
{
"brands": [
{
"id": "fe877b45-8620-453a-8805-63f0cbd80752",
"name": "no brand",
"slug": "no-brand",
"description": null,
"photo": null,
"created_at": "2020-07-15 11:35:18",
"updated_at": "2020-07-15 11:35:18"
}
],
"options": [
{
"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"parent_id": null,
"name": "need insurance?",
"slug": "need-insurance",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 11:28:09",
"updated_at": "2020-07-17 11:28:09",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"option_id": "324af955-1aa9-42ea-be6e-bb4e5623a97a"
},
"children": [
{
"id": "44afca9e-abf1-4a7a-9c46-d96d8127c2af",
"parent_id": "324af955-1aa9-42ea-be6e-bb4e5623a97a",
"name": "No",
"slug": "no",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 11:28:09",
"updated_at": "2020-07-17 11:28:09"
}
]
},
{
"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"parent_id": null,
"name": "color",
"slug": "color",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"option_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b"
},
"children": [
{
"id": "29b62f35-52a2-4a8b-ac8f-7e70e065488a",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Black",
"slug": "black",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "4aa2d899-f1cc-4000-95e6-997d28dc51fc",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Red",
"slug": "red",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "5f9de5bc-e966-48f3-b78c-de709dba86b5",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "Gray",
"slug": "gray",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
},
{
"id": "f248d6ab-1b88-4ea4-8d6a-62fe271bfa8a",
"parent_id": "73298c18-4ccc-4138-afa5-71d3d00dff9b",
"name": "White",
"slug": "white",
"photo": null,
"type": "dropdown",
"active": "yes",
"created_at": "2020-07-17 11:27:41",
"updated_at": "2020-07-17 11:27:41"
}
]
},
{
"id": "522da418-eb3f-43e9-9392-63c941842a52",
"parent_id": null,
"name": "color",
"slug": "color-3",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"option_id": "522da418-eb3f-43e9-9392-63c941842a52"
},
"children": [
{
"id": "84135f25-690b-407b-8c98-e7526429a594",
"parent_id": "522da418-eb3f-43e9-9392-63c941842a52",
"name": "Red",
"slug": "red-3",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46"
},
{
"id": "9d1f0d9c-272a-4e96-ac0a-aeac869bfc30",
"parent_id": "522da418-eb3f-43e9-9392-63c941842a52",
"name": "Yellow",
"slug": "yellow-2",
"photo": null,
"type": "radio",
"active": "yes",
"created_at": "2020-07-17 12:20:46",
"updated_at": "2020-07-17 12:20:46"
}
]
}
],
"ratings": [
"4.5",
"4.0"
],
"tags": [
{
"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f",
"name": "options",
"slug": "options",
"photo": null,
"active": "yes",
"created_at": "2020-07-17 11:29:47",
"updated_at": "2020-07-17 11:29:47",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"tag_id": "8a31ee4c-3302-4357-9686-bd4308bbf39f"
}
},
{
"id": "94ef99b6-ed2a-4eea-9248-e4775159eb58",
"name": "product",
"slug": "product",
"photo": null,
"active": "yes",
"created_at": "2020-07-17 11:29:47",
"updated_at": "2020-07-17 11:29:47",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"tag_id": "94ef99b6-ed2a-4eea-9248-e4775159eb58"
}
},
{
"id": "378802b3-d13a-48c4-afa2-f9fed94d69ee",
"name": "werg",
"slug": "werg",
"photo": null,
"active": "yes",
"created_at": "2020-07-15 11:53:13",
"updated_at": "2020-07-15 11:53:13",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"tag_id": "378802b3-d13a-48c4-afa2-f9fed94d69ee"
}
},
{
"id": "f1380f50-af59-4f6a-8eca-d40689c1c1c1",
"name": "werwg",
"slug": "werwg",
"photo": null,
"active": "yes",
"created_at": "2020-07-15 11:53:13",
"updated_at": "2020-07-15 11:53:13",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"tag_id": "f1380f50-af59-4f6a-8eca-d40689c1c1c1"
}
}
],
"variations": [
{
"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"parent_id": null,
"name": "ram",
"slug": "ram",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:05",
"updated_at": "2020-07-17 11:27:05",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3"
},
"children": [
{
"id": "5687d6a8-12df-41b2-bf2f-b822faae8af0",
"parent_id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3",
"name": "4 Gig",
"slug": "4 Gig",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:05",
"updated_at": "2020-07-17 11:27:05"
}
]
},
{
"id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"parent_id": null,
"name": "cpu",
"slug": "cpu",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:26:58",
"updated_at": "2020-07-17 11:26:58",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "e5c70766-a558-4539-b41f-77f72c819a7c"
},
"children": [
{
"id": "83003a24-cc69-4305-8d3a-e99da91d3354",
"parent_id": "e5c70766-a558-4539-b41f-77f72c819a7c",
"name": "Core i7",
"slug": "Core i7",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:26:58",
"updated_at": "2020-07-17 11:26:58"
}
]
},
{
"id": "e63ac831-f595-4889-83d2-a5be65734758",
"parent_id": null,
"name": "monitor",
"slug": "monitor",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:21",
"updated_at": "2020-07-17 11:27:21",
"pivot": {
"product_id": "293c0369-04a7-4330-bb98-ede0bcf10f8d",
"variant_id": "e63ac831-f595-4889-83d2-a5be65734758"
},
"children": [
{
"id": "816e1fab-24eb-49e9-9b3a-d4b4cce16cdf",
"parent_id": "e63ac831-f595-4889-83d2-a5be65734758",
"name": "14\"",
"slug": "14\"",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 11:27:21",
"updated_at": "2020-07-17 11:27:21"
}
]
},
{
"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"parent_id": null,
"name": "cpu",
"slug": "cpu-3",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 12:20:56",
"updated_at": "2020-07-17 12:20:56",
"pivot": {
"product_id": "a8bb27c8-e968-4317-b4d2-8e5cd6049ff8",
"variant_id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea"
},
"children": [
{
"id": "50857808-106e-4ae0-8c02-a54761e6dac7",
"parent_id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea",
"name": "Core i3",
"slug": "Core i3-2",
"photo": null,
"type": "input",
"active": "yes",
"created_at": "2020-07-17 12:20:56",
"updated_at": "2020-07-17 12:20:56"
}
]
}
]
}
You can achieve what you want in one iteration over the data using reduce like so:
$variations = [];
$result = array_reduce($filters, function ($result, $filter) use ($variations) {
$filter['brand']['name'] = strtolower($filter['brand']['name']);
if ($result['brands']->where('name', $filter['brand']['name'])->isEmpty()) {
$result['brands']->push($filter['brand']);
}
foreach ($filter['options'] as $option) {
$option['name'] = strtolower($option['name']);
if ($result['options']->where('name', $option['name'])->isEmpty()) {
$result['options']->push($option);
}
}
if (isset($filter['rating']['id'])) {
if ($result['ratings']->where('id', $filter['rating']['id'])->isEmpty()) {
$result['ratings']->push($filter['rating']);
}
}
foreach ($filter['tags'] as $tag) {
$tag['name'] = strtolower($tag['name']);
if ($result['tags']->where('name', $tag['name'])->isEmpty()) {
$result['tags']->push($tag);
}
}
foreach ($filter['variations'] as $variation) {
$variation['name'] = strtolower($variation['name']);
$variationName = $variation['name'];
$children = collect($variation['children'])->pluck('name');
if ($result['variations']->where('name', $variation['name'])->isEmpty()) {
$result['variations']->push($variation);
$variations[$variationName] = $children;
} else {
$different = $variations[$variationName]->diff($children);
if ($different->isNotEmpty()) {
$result['variations']->push($variation);
foreach ($different as $childName) {
$variations[$variationName]->push($childName);
}
}
}
}
return $result;
}, collect([
'brands' => collect(),
'options' => collect(),
'ratings' => collect(),
'tags' => collect(),
'variations' => collect()
]));
If you need the result as an array, you can use the collection's toArray method:
$result->toArray();
I have added a sample code with a row json data based on your input
$jsonData = '[{
"brand": {"id": "fe877b45-8620-453a-8805-63f0cbd80752", "name": "No Brand", "slug": "no-brand", "description": "null"},
"options": [{"id": "324af955-1aa9-42ea-be6e-bb4e5623a97a", "parent_id": "null", "name": "Need Insurance?"},
{"id": "73298c18-4ccc-4138-afa5-71d3d00dff9b", "parent_id": "null", "name": "Color", "slug": "color"}],
"rating": [],
"tags": [{"id": "8a31ee4c-3302-4357-9686-bd4308bbf39f", "name": "options", "slug": "options", "photo": "null"}],
"variations": [{"id": "3bf5aeb9-9da2-4fb1-a3d2-f89eb75839c3", "parent_id": "null", "name": "Ram", "slug": "ram", "photo": "null"},
{"id": "e5c70766-a558-4539-b41f-77f72c819a7c", "parent_id": "null", "name": "cpu", "slug": "cpu", "photo": "null"},
{"id": "e63ac831-f595-4889-83d2-a5be65734758", "parent_id": "null", "name": "Monitor", "slug": "monitor"}
]
},
{
"brand": {"id": "fe877b45-8620-453a-8805-63f0cbd80752", "name": "No Brand", "slug": "no-brand", "description": null},
"options": [{"id": "522da418-eb3f-43e9-9392-63c941842a52", "parent_id": null, "name": "Color", "slug": "color-3"}],
"rating": [],
"tags": [],
"variations": [{"id": "8e9a26c5-2ee4-4d86-9244-a10596d67fea", "parent_id": null, "name": "Cpu", "slug": "cpu-3", "photo": null}]
}
]
';
$jsonDataArr =json_decode($jsonData);
$data = array();
foreach($jsonDataArr as $key => $items){
foreach($items as $innerKey => $eachItem){
if(!isset($data[$innerKey])){
$data[$innerKey] = array();
if(is_array($eachItem)){
foreach($eachItem as $each)
if(!empty($each))
$data[$innerKey][] = (array) $each;
}else{
if(!empty($eachItem))
$data[$innerKey][] = (array) $eachItem;
}
}else{
if(is_array($eachItem)){
foreach($eachItem as $each)
if(!empty($each))
$data[$innerKey][] = (array) $each;
}else{
if(!empty($eachItem))
$data[$innerKey][] = (array) $eachItem;
}
}
}
}
foreach($data as $key => $val){
foreach($val as $l => $item){
$index = trim(strtolower($item['name']));
$data[$key][$index] = $item;
unset($data[$key][$l]);
}
}
foreach($data as $key => $val){
$data[$key]=array_values($val);
}
print_r($data);
Demo

Is it possible extract and merge a single json object from multiple json files?

Sorry for the confusing title. I am having a bit of an issue here merging some JSON files. I need to merge all the products into one array in a separate file.
I have a directory full of same structured json files. I am using glob to select all files and decode->append-->encode json files into one large file.
Here is my code:
<?php
$files = glob("*.json");
$newDataArray = [];
foreach($files as $file){
$thisData = file_get_contents($file);
$thisDataArray = json_decode($thisData);
$newDataArray[] = $thisDataArray;
}
$newDataJSON = json_encode($newDataArray);
file_put_contents("merged.json",$newDataJSON);
?>
Now, the above code seems to work great but I only want to extract all the products.
Quick example of what I need to achieve.
File1.json
{
"status": true,
"user": {
"username": "sally",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "35vR4hr",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "na1Id4t",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
File2.json
{
"status": true,
"user": {
"username": "Jessica",
"avatar": "/images/default-avatar.png",
"products": [
{
"id": "wjiefi94",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
}
I want the data to be merged like:
merged.json
{
"products": [
{
"id": "wjiefi94",
"title": "Picture 1",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 2,
"currency": "CAD",
"stock_warning": 1,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 2",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 3",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
},
{
"id": "n34idwi",
"title": "Picture 4",
"image": null,
"quantity": {
"min": 1,
"max": 1
},
"price": 0.75,
"currency": "CAD",
"stock_warning": 3,
"type": "service",
"stock": 9223372036854776000
}
]
}
I hope this makes sense. I feel like I have hit a dead end here. Any help is greatly appreciated.
would it be possible for you to call an external tool like "jq"? handling json (just like csv), especially with many files, is not something you should be doing manually.
btw, your example does not have commas between products 2 and 3 and 3 and 4.
Your new code on line 5 should probably read like this with the array brackets? Otherwise you are overwriting the contents of the last files:
$thisDataArray[] = json_decode($thisData);
And why are you merging products from Sally and Jessica into the same user? Maybe you can just extract all the products objects into one file?
More of a code review than an answer, hope it helps ;)

Subscribed topics

In my forum I'm showing all topics. It looks like this:
So a user can subscribe by clicking on the red hearth.
I'm loading the topics with this json:
{
"forum": {
"id": 1,
"slug": "test",
"name": "test",
"description": "test",
"created_at": null,
"updated_at": null
},
"topics": {
"total": 6,
"per_page": 5,
"current_page": 1,
"last_page": 2,
"next_page_url": "http://forum.dev/api/forum/test?page=2",
"prev_page_url": null,
"from": 1,
"to": 5,
"data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 2,
"slug": "2",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 3,
"slug": "1",
"name": "1",
"description": "1\t",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 4,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
},
{
"id": 5,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null
}
]
}
}
I'm returning that ^ like this:
$forum->topics()->orderBy('created_at', 'DESC')->paginate(5);
So how do I get a subscribe value on every topic object?
So like this:
"data": [
{
"id": 1,
"slug": "1",
"name": "1",
"description": "1",
"forum_id": 1,
"created_at": null,
"updated_at": null,
"subscribed": true
},
I already made this on my topic model:
/**
* #return mixed
*/
public function subscriptions()
{
return Topic::subscribedBy(Auth::user())->get();
}
And it's working. But how do I send that ^ with every topic.
You can add an attribute (which is not present in the database) by creating an accessor.
public function getSubscriptionsAttribute()
{
return Topic::subscribedBy(Auth::user())->get();
}
and then adding it to the $append property.
protected $appends = ['subscriptions'];
If you're using the $visible whitelist you might have to add it to that property too.
Source (Its all the way in the bottom.)

Obtaining the last level of a json tree on php

I have a json tree with categories,
I would like to obtain the last level of elements for each different category.
For example on this json:
[
{
"category_id": "3",
"parent_id": "2",
"name": "Women",
"categories": [
{
"category_id": "11",
"parent_id": "3",
"name": "Clothing",
"categories": [
{
"category_id": "30",
"parent_id": "11",
"name": "T-shirts",
"categories": null
},
{
"category_id": "33",
"parent_id": "11",
"name": "jeans",
"categories": null
}
]
}
]
},
{
"category_id": "5",
"parent_id": "2",
"name": "Footwear ",
"categories": [
{
"category_id": "15",
"parent_id": "5",
"name": "Rings",
"categories": [
{
"category_id": "51",
"parent_id": "15",
"name": "Small Leathers",
"categories": null
}
]
},
{
"category_id": "16",
"parent_id": "5",
"name": "Bands",
"categories": [
{
"category_id": "41",
"parent_id": "16",
"name": "boots",
"categories": null
}
]
},
{
"category_id": "48",
"parent_id": "5",
"name": "Bracelets",
"categories": [
{
"category_id": "55",
"parent_id": "48",
"name": "Cocktail",
"categories": null
}
]
}
]
}
]
The result would be an array (T-shirts, Jeans, Small Leathers, boots, cocktail)
What I was thinking is to decode it on an array and search filter the array with all the categories that are null, but I'm not sure if it's the best option because the object have different levels.
(I'm sorry for the English)
Json string is not a valid. It can be made valid by enclosing the json string in {}.
$json = '{"categories": [
{
"category_id": "3",
"parent_id": "2",
"name": "Women",
"categories": [
{
"category_id": "11",
"parent_id": "3",
"name": "Clothing",
"categories": [
{
"category_id": "30",
"parent_id": "11",
"name": "T-shirts",
"categories": null
},
{
"category_id": "33",
"parent_id": "11",
"name": "jeans",
"categories": null
}
]
}
]
},
{
"category_id": "5",
"parent_id": "2",
"name": "Footwear ",
"categories": [
{
"category_id": "15",
"parent_id": "5",
"name": "Rings",
"categories": [
{
"category_id": "51",
"parent_id": "15",
"name": "Small Leathers",
"categories": null
}
]
},
{
"category_id": "16",
"parent_id": "5",
"name": "Bands",
"categories": [
{
"category_id": "41",
"parent_id": "16",
"name": "boots",
"categories": null
}
]
},
{
"category_id": "48",
"parent_id": "5",
"name": "Bracelets",
"categories": [
{
"category_id": "55",
"parent_id": "48",
"name": "Cocktail",
"categories": null
}
]
}
]
}
]}';
Decode the json string in to php opject
$json_object = json_decode($json);
Use this recursive function to fetch get all the last level categories in a array.
function getLastCategories($object){
$last_categories = array();
if(is_array($object->categories)){
foreach($object->categories as $categories){
$last_categories = array_merge( $last_categories, getLastCategories($categories));
}
}else{
$last_categories[]=$object->name;
}
return $last_categories;
}
print_r(getLastCategories($json_object));
Output:
Array
(
[0] => T-shirts
[1] => jeans
[2] => Small Leathers
[3] => boots
[4] => Cocktail
)
You can do this using recursive iterators.
$categories = json_decode($json);
// create the iterator
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($categories));
// iterate recursively
foreach ($iterator as $key => $subcategories) {
// if the 'categories' key is empty for the current level...
if ($key == 'categories' && !$subcategories) {
// then add the value of the 'name' key for the current level to your result array.
$result[] = $iterator->getSubIterator()->offsetGet('name');
}
}
This may not be the most efficient way to do it, but it makes the code pretty simple.

Categories