Merge 2 arrays based on a common element - php

So I have a Laravel controller that is pulling in 2 arrays.
Array 1:
[
{
"id":1,
"created_at":null,
"updated_at":null,
"name":"The Darkroom",
"description":"This is the room your parents warned you about",
"image":"https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80",
"is_private":"0"
},{
"id":2,
"created_at":null,
"updated_at":null,
"name":"Smoking & Cigars",
"description":"Time to light up and enjoy a cigar!",
"image":"https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80",
"is_private":"0"
},{
"id":3,
"created_at":null,
"updated_at":null,
"name":"Humiliation",
"description":"today is the day you are going to be exposed",
"image":"https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80",
"is_private":"1"
},{
"id":4,
"created_at":null,
"updated_at":null,
"name":"Financial Domination",
"description":"hand over your cash and say thank you Sir!",
"image":"https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80",
"is_private":"0"
},{"id":5,"created_at":null,"updated_at":null,"name":"Pups & Handlers","description":"Woof, woof, bark, sit","image":"https:\/\/images.unsplash.com\/photo-1506939754500-f27bc71fccd4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"1"}]
Array 2:
{"channels":{"presence-chat.1":{"user_count":1},"presence-chat.4":{"user_count":1}}}
Final Array should look like this:
[
{
"id":1
"other data in the first array"
"user_count": 1
}
]
What I NEED to do inside my controller is merge the data together into a single array. So ideally, take the second array, match up the chat.ID with the ID of the first array and add in user_count to it... well you get what I mean.
I Have NEVER done this before so I have NO IDEA how best to go about this. Any help would be forever appreciated!

Here you go, this assumes that presence-chat.4 means channel with the id of 4:
<?php
$json1 = '[{"id":1,"created_at":null,"updated_at":null,"name":"The Darkroom","description":"This is the room your parents warned you about","image":"https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80","is_private":"0"},{"id":2,"created_at":null,"updated_at":null,"name":"Smoking & Cigars","description":"Time to light up and enjoy a cigar!","image":"https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80","is_private":"0"},{"id":3,"created_at":null,"updated_at":null,"name":"Humiliation","description":"today is the day you are going to be exposed","image":"https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80","is_private":"1"},{"id":4,"created_at":null,"updated_at":null,"name":"Financial Domination","description":"hand over your cash and say thank you Sir!","image":"https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"0"},{"id":5,"created_at":null,"updated_at":null,"name":"Pups & Handlers","description":"Woof, woof, bark, sit","image":"https:\/\/images.unsplash.com\/photo-1506939754500-f27bc71fccd4?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80","is_private":"1"}]';
$json2 = '{"channels":{"presence-chat.1":{"user_count":1},"presence-chat.4":{"user_count":1}}}';
// convert the json into php arrays
$array1 = json_decode($json1, true);
$array2 = json_decode($json2, true);
// we extract the user_counts from the second array
// and make the index of a new array the channel id with value user_count
$channel_counts = [];
foreach ($array2['channels'] as $chan_name => $count) {
$channel_id = explode('.', $chan_name)[1];
$user_count = $count['user_count'];
$channel_counts[$channel_id] = $user_count;
}
// we pass this array by reference as we are modifying it
foreach ($array1 as &$channel) {
$id = $channel['id'];
if (isset($channel_counts[$id]))
$channel['user_count'] = $channel_counts[$id];
else
$channel['user_count'] = 0;
}
unset($channel);
$final_json = json_encode($array1, JSON_PRETTY_PRINT);
echo $final_json;
Which results in:
[
{
"id": 1,
"created_at": null,
"updated_at": null,
"name": "The Darkroom",
"description": "This is the room your parents warned you about",
"image": "https:\/\/images.unsplash.com\/photo-1579662908513-50e1433a258a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1234&q=80",
"is_private": "0",
"user_count": 1
},
{
"id": 2,
"created_at": null,
"updated_at": null,
"name": "Smoking & Cigars",
"description": "Time to light up and enjoy a cigar!",
"image": "https:\/\/images.unsplash.com\/photo-1617850136763-06bc0a9a089c?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2000&q=80",
"is_private": "0",
"user_count": 0
},
{
"id": 3,
"created_at": null,
"updated_at": null,
"name": "Humiliation",
"description": "today is the day you are going to be exposed",
"image": "https:\/\/images.unsplash.com\/photo-1571570261702-3d23956fa32e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2600&q=80",
"is_private": "1",
"user_count": 0
},
{
"id": 4,
"created_at": null,
"updated_at": null,
"name": "Financial Domination",
"description": "hand over your cash and say thank you Sir!",
"image": "https:\/\/images.unsplash.com\/photo-1526304640581-d334cdbbf45e?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=2200&q=80",
"is_private": "0",
"user_count": 1
}, ...snip
]

Related

Getting Duplicate Data on Response On Laravel Eloquent

I am new in laravel in php. So it might be very silly mistake. I have song table and song categories table. I am trying to fetch all category with their respective songs. I have implemented larvel eloquent one to many relationship between song category and song.
Here is my code of fetching data:
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
# code...
$json = [];
$json['category'] = $item;
$json['songs'] = $item->songs;
array_push($json_array,$json);
}
return $json_array;
}
Here is response:
[{
"category": {
"id": 1,
"title": "Rock",
"created_at": "2020-12-20T02:58:32.000000Z",
"updated_at": "2020-12-20T02:58:32.000000Z",
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}
}, {
"songs": [{
"id": 1,
"title": "Mere Mehboob",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/2u039f-a.akamaihd.net\/downloads\/ringtones\/files\/mp3\/mere-mehboob-qayamat-hogi-52150.mp3",
"created_at": "2020-12-20T13:26:30.000000Z",
"updated_at": "2020-12-20T13:26:30.000000Z"
}, {
"id": 2,
"title": " Taaron Ke Shehar",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/TaaronKeSheharRingtoneByNehaKakkarJubinNautiyal2145436126.mp3",
"created_at": null,
"updated_at": null
}, {
"id": 3,
"title": "Bewafa Tera Masoom Chehra",
"thumbnail": "https:\/\/static.toiimg.com\/photo\/msid-71407401\/71407401.jpg?108311",
"song_category_id": 1,
"stream_link": "https:\/\/newmp3ringtones.net\/assets\/sass\/Ringtones\/BewafaTeraMasoomChehraRingtoneByJubinNautiyal352778308.mp3",
"created_at": null,
"updated_at": null
}]
}, {
"category": {
"id": 2,
"title": "Soft",
"created_at": null,
"updated_at": null,
"songs": []
}
}, {
"songs": []
}]
As you can see songs get repeated.
UPDATE
Solved using eager loading
public function getSongCategoriesWithSongs(){
return SongCategory::with('songs')->get();
}
But don't know why the foreach method not working.
Try this code
public function getSongCategoriesWithSongs(){
$json_array = array();
$song_categories = SongCategory::all();
foreach ($song_categories as $item) {
$json_array[] = ['category' => $item, 'songs' => $item->songs] ;
}
return $json_array;
}
The problem is that you assign the same relation twice.
Each SongCategory already has a collection of songs inside.
So in your foreach block, you assign a category with $json['category'] => $item which will load all related songs and pass them to the final JSON object. And you duplicate this by passing the next item $json['songs'] = $item->songs to the same array. Default Laravel behavior will be to fetch all related objects and transform them into JSON.
I would suggest you to use Laravel resources to return JSON objects with exact shapes: API Resources.
You can fix your code block without eager loading by removing $json['songs'] = $item->songs assignment.
Eager loading works because you passed all your objects only once.

Delete unwanted data from api result

I have a project in laravel which has API. I'm asking the API for posts(I call them recommendation).
Now my api response look like this -
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
...
...
...
All is good but I don't wanna likes_count to be in the result. It is a relation method. I get from it all I need. It is if the user liked this post. And it is is_liked in the result . but likes_count automatically added to the response .
if($item->likesCount->contains($user->id)){
$item['is_liked']='true';
}
I tried delete it with
foreach ($recommendations as $item) {
unset($item['likes_count']);
}
But it doesn't do it.
I think the problem is how you are referencing the object data structure. You are attempting to unset() something that doesn't exist so no error is thrown but the likes_count isn't getting removed either.
Here's your code example (fixed and modified for demonstration):
<?php
$apiResult = <<<eod
{
"success": true,
"data": {
"current_page": 1,
"data": [
{
"id": 3,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
},
{
"id": 4,
"course_id": "20",
"title": "Dormouse followed.",
"description": "Alice aloud, addres",
"file": "https://example.com/storage/images/2019/10/01/phTJ.png",
"created_at": null,
"updated_at": "2019-10-01 14:21:46",
"recommendation_likes": 0,
"is_bookmarked": "true",
"is_liked": "false",
"likes_count": []
}
]
}
}
eod;
$result = json_decode($apiResult);
$data = $result->data->data;
var_dump($data);
// This should remove the likes_count array from the $result structure.
foreach ($data as &$item) {
unset($item->likes_count);
}
var_dump($data);
A quick way would be to make that 'attribute' (relation) hidden:
$recommendations->makeHidden('likes_count');
Though I am not sure how you are building your response.

Parsing json key value in PHP (multidimensional array)

By now I think I 'tried' just about all of the suggested ways to parse the value of one or more keys from a POST response. I've been able to boil it down a little but I'd super appreciate any help someone would be willing to give. My goal is to retrieve the value of the "id" and "campaign_id" keys (or any other key value for that matter). Needless to say I'm at a beginners level ˆ_ˆ
here we go..
$contents = ($this->response);
$enc = ($contents);
results into:
Array ( [0] => [ { "url": "http://www.aguabenito.com", "name": "Bikinis - New arrivals", "prefix": "AGUA", "notes": "", "updated_at": "2017-01-14 16:26:35", "created_at": "2017-01-14 16:26:35", "id": 4609 }, [], [ { "id": 3531, "url_code": "R0uvzO", "alias": null, "campaign_id": 4609, "paidchannel_id": 104, "deleted_at": null, "created_at": "2017-01-14 16:26:35", "updated_at": "2017-01-14 16:26:35" } ] ] )
and then..
for ($i = 0; $i < count($enc); ++$i) {
print $enc[$i];
}
results into:
[
{
"url": "http://www.aguabenito.com",
"name": "Bikinis - New arrivals",
"prefix": "AGUA",
"notes": "",
"updated_at": "2017-01-14 16:26:35",
"created_at": "2017-01-14 16:26:35",
"id": 4609
},
[],
[
{
"id": 3531,
"url_code": "R0uvzO",
"alias": null,
"campaign_id": 4609,
"paidchannel_id": 104,
"deleted_at": null,
"created_at": "2017-01-14 16:26:35",
"updated_at": "2017-01-14 16:26:35"
}
]
I'm afraid to say that I'm just going around in circles from here onwards. When I try to get any of the values I keep getting Illegal string offset or Undefined index errors. Really hoping to learn what I'm doing wrong and how I should go about retrieving the value of one or more of these keys.
Hoping to achieve something in the lines of:
$campaign_id = '4609';
$first_urlcode = 'R0uvzO';
$first_urlcode_id = '3531';
$second_urlcode = 'abc123';
$second_urlcode_id = '1234';
Thanks #EatPienutButter for helping me out!!
This got me walking straight again )))))
$enc = json_decode($contents[0], true);
$campaignid = ($enc[0]['id']);
$first_urlcode = ($enc[2][0]['url_code']);
$first_urlcode_id = ($enc[2][0]['id']);

Eloquent - Group By Month, Year and Paginate

I am trying to list entries in a table by Month, Year:
May, 2015
Item 1
Item 2
Item 3
June, 2015
Item 1
etc..
I have achieved this with the following code but I would also like to paginate the results. I have tried many different things but none of them seem to work, I am using Laravel 5.
$events = App\Events->orderBy('start', 'asc')->get()->groupBy(function($date) {
return $date->start->format('F, Y');
});
Here is the output for the above query:
{
"April, 2015": [
{
"id": "10",
"event_type_id": "1",
"user_id": "1",
"title": "Testing",
"slug": "testing",
"start": "2015-04-23 17:00:00",
"end": "2015-04-23 17:40:00",
"description": "<h1>MEETING!</h1><p>Let's try this in HTML!<br></p>",
"created_at": "2015-04-19 14:18:33",
"updated_at": "2015-04-21 22:07:41",
"type": {
"id": "1",
"name": "General",
"slug": "general",
"created_at": "2015-04-18 11:24:00",
"updated_at": "2015-04-18 11:24:04"
}
}
],
"May, 2015": [
{
"id": "12",
"event_type_id": "1",
"user_id": "1",
"title": "Test Event",
"slug": "test-event",
"start": "2015-05-15 18:00:00",
"end": null,
"description": "<p>This is a test event with just a start time</p>",
"created_at": "2015-04-21 14:59:56",
"updated_at": "2015-05-02 18:37:53",
"type": {
"id": "1",
"name": "General",
"slug": "general",
"created_at": "2015-04-18 11:24:00",
"updated_at": "2015-04-18 11:24:04"
}
},
{
"id": "9",
"event_type_id": "1",
"user_id": "1",
"title": "Monthly Meeting",
"slug": "monthly-meeting",
"start": "2015-05-23 14:00:00",
"end": "2015-04-16 20:00:00",
"description": "<p>It's a long monthly meeting!</p>",
"created_at": "2015-04-19 13:13:45",
"updated_at": "2015-05-03 08:45:56",
"type": {
"id": "1",
"name": "General",
"slug": "general",
"created_at": "2015-04-18 11:24:00",
"updated_at": "2015-04-18 11:24:04"
}
}
],
"June, 2015": [
{
"id": "11",
"event_type_id": "1",
"user_id": "1",
"title": "Another Meeting Saved",
"slug": "another-meeting-saved",
"start": "2015-06-19 18:00:00",
"end": null,
"description": "<p>It's another meeting afterall</p>",
"created_at": "2015-04-20 15:03:30",
"updated_at": "2015-05-03 08:46:19",
"type": {
"id": "1",
"name": "General",
"slug": "general",
"created_at": "2015-04-18 11:24:00",
"updated_at": "2015-04-18 11:24:04"
}
}
]
}
With LengthAwarePaginator -
$paginator = new LengthAwarePaginator($events, count($events), 1);
return $paginator;
This returns the paginator but the data is the same - meaning the same result set as without the paginator, when I'd expect only one record to be returned per page:
[{
"total": 3,
"per_page": 1,
"current_page": 1,
"last_page": 3,
"next_page_url": "/?page=2",
"prev_page_url": null,
"from": 1,
"to": 3,
"data": {
"data" : ".. same as above"
}
}]
With aggregates you need to implement your own custom paginator, as stated by docs:
Note: Currently, pagination operations that use a groupBy statement
cannot be executed efficiently by Laravel. If you need to use a
groupBy with a paginated result set, it is recommended that you query
the database and create a paginator manually.
See this posts to manually implement pagination:
Laravel 5 - Manual pagination
Manually Creating a Paginator (Laravel 5)
Many people have pointed me to a widely mentioned paragraph in the Laravel documentation,
Note: Currently, pagination operations that use a groupBy statement
cannot be executed efficiently by Laravel. If you need to use a
groupBy with a paginated result set, it is recommended that you query
the database and create a paginator manually.
Not terribly helpful, since I cannot find any example in the documentation as to exactly how to create a manual paginator using the results of an Eloquent query. So, here is what I was able to come up with. Note that you must use ->take() and ->offset() in the query, otherwise you will end up with the same results on every page (this is where I was getting stuck).
<?php
// routes.php
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
get('test', function(Request $request) {
$page = $request->has('page') ? $request->input('page') : 1; // Use ?page=x if given, otherwise start at 1
$numPerPage = 2; // Number of results per page
$eventType = EventType::find(1); // Not relevant to pagination
$count = $eventType->memberEvents()->count(); // Get the total number of entries you'll be paging through
// Get the actual items
$events = $eventType->memberEvents()->orderBy('start', 'asc')
->take($numPerPage)->offset(($page-1)*$numPerPage)->get()->groupBy(function($date) {
return $date->start->format('F, Y');
});
// Create the paginator with Illuminate\Pagination\LengthAwarePaginator as Paginator
// Pass in the variables supplied above, including the path for pagination links
$paginator = new Paginator($events, $count, $numPerPage, $page, ['path' => $request->url(), 'query' => $request->query()]);
return $paginator;
});
If you want to add groupBy to your data the you should use LengthAwarePaginator object as updated in laravel 5
Try this,
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
$page = ($request->input('page') != null) ? $request->input('page') : 1;
$perPage = 1;
$sliced = array_slice($data, 0, 5); //you can these values as per your requirement
$paginator = new Paginator($sliced, count($data), $perPage, $page,['path' => url()->current(),'query' => $request->query()]);
return $paginator;
$data is your data object and fifth parameters are for next and prev urls
Refer this for more information about paginator,
https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Builder.html#method_paginate
As stated in the Laravel docs...Note: Currently, pagination operations that use a groupBy statement cannot be executed efficiently by Laravel. If you need to use a groupBy with a paginated result set, it is recommended that you query the database and create a paginator manually. Docs

Searching an array and getting results

Okay, So I am wanting to find information in an array and get a block returned based on the credentials passed. The way I am doing it right now is not working, I'm looking for a shorter process and a more fool proof process.
Right now I have this:
public function get_product($product_id, $color, $size)
{
$results = $this->pf->get('products/'.$product_id);
$vars = $results['variants'];
$details = array();
foreach($vars as $var)
{
if(!in_array($product_id, $details))
{
if($var['product_id'] == $product_id)
{
if($var['size'] == $size)
{
if($var['color'] == $color)
{
$details[$var['id']] = array(
'id' => $var['id'],
'name' => $var['name'],
'image' => $var['image'],
'price' => $var['price'],
);
}
}
}
}
}
return $details;
}
This receives a product_id, a color, and a size. Sometimes $color is null, Sometimes $size is null, and sometimes both $color and $size are null and we just need to find the one array that matches the $product_id.
What I am wanting returned is this:
$details[$var['id']] = array(
'id' => $var['id'],
'name' => $var['name'],
'image' => $var['image'],
'price' => $var['price'],
);
Right now nothing gets returned. $results returns this for an example: (This is what I need to search.)
{
"code": 200,
"result": {
"product": {
"id": 1,
"type": "POSTER",
"brand": null,
"model": "Poster",
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/poster_18x24.jpg",
"variant_count": 9,
"files": [
{
"id": "default",
"title": "Print file",
"additional_price": null
},
{
"id": "preview",
"title": "Mockup",
"additional_price": null
}
],
"options": []
},
"variants": [
{
"id": 4464,
"product_id": 1,
"name": "Poster 12×12",
"size": "12×12",
"color": null,
"color_code": null,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/1/4464.jpg",
"price": "9.00"
},
Notice how color is returned as null. size can be that way to. So basically I am wanting a quicker and better way to search the returned array for the specified product_id, size, and color. So I need returned and matching the corresponding variants block that matches the variables submitted.
I hope I've made sense of what I'm trying to accomplish.
UPDATE
This is what I am needing.
So on my site the customers chooses a product, in this case a poster. Before adding it to the cart they are prompted to select a size. Let's say a 12x12. The way the API works is that it has a "top" item and then has smaller items "variants" that include the size and color. Each variant is a poster with a different size. The only way to obtain the poster product, is by receiving every variant for the poster. But each "variant" has a different "id" to send to the api to order the correct product.
So, I receive the product and it's variants in bulk or every color and size as it's own variant.
"variants": [
{
"id": 4464,
"product_id": 1,
"name": "Poster 12×12",
"size": "12×12",
"color": null,
"color_code": null,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/1/4464.jpg",
"price": "9.00"
},
{
"id": 1349,
"product_id": 1,
"name": "Poster 12×16",
"size": "12×16",
"color": null,
"color_code": null,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/1/1349.jpg",
"price": "11.00"
},
But remember the customer wanted a poster that was 12x12? We only need to send the demand to print a 12x12 poster. So we need to send to the api the ID for the variant that matches the 12x12 size.
I need a way to search through each variant for a product and find the correct variant that matches the product_id of the poster, and the size requirements of 12x12.
{
"id": 4464,
"product_id": 1,
"name": "Poster 12×12",
"size": "12×12",
"color": null,
"color_code": null,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/1/4464.jpg",
"price": "9.00"
},
Once I find that correct variant, I need to collect all that information into a new array and return it.
//Get the product based on the supplied product_id. ($results)
//Break that array down into just the variants. ($vars)
//Search the $vars array for a block that matches the product_id.
//Search those $vars blocks for a single one that matches the size.
//If color is supplied, search those $vars blocks for a single one that matches the color.
//If size and color are supplied, a single block should be returned that matches all three variables (product_id, size, and color). Sometimes size and/or color is `null`. But a product_id is always supplied.
I hope the clears up what I am needing a little better.
Try this. Am also ssuming you are using php. If you have a question, asking me directly. I think I can help you but I don't know exactly what you want.
<?php
function get_product($object){
$result = json_decode($object);
$product_id = $result->result->product->id;
$variants = $result->result->variants;
$details = array();
foreach($variants as $variant):
$details[] = $variant;
endforeach;// foreach
return $details;
}
$json_obj = '{
"code": 200,
"result": {
"product": {
"id": 1,
"type": "POSTER",
"brand": null,
"model": "Poster",
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/poster_18x24.jpg",
"variant_count": 9,
"files": [
{
"id": "default",
"title": "Print file",
"additional_price": null
},
{
"id": "preview",
"title": "Mockup",
"additional_price": null
}
],
"options": []
},
"variants": [
{
"id": 4464,
"product_id": 1,
"name": "Poster 12×12",
"size": "12×12",
"color": null,
"color_code": null,
"image": "https://d1yg28hrivmbqm.cloudfront.net/products/1/4464.jpg",
"price": "9.00"
}
]
}
}';
$array = json_decode($json_obj);
echo '<pre>';
print_r(get_product($json_obj));
echo '</pre>';

Categories