How to insert nested array of a multidimensional array into mysql - php

I have a multidimensional aray that i want to insert into mysql database. Everything works fine but iwant a better solution as the rows repeat itself following the nested array
here is my json
{
"results": [
{
"id": 48728,
"name": "MOVIES AT THE PARK # GIBA GORGE",
"url": "Some URL",
"imageUrl": "Some Path",
"dateCreated": "2018-06-08T09:18:59.717",
"lastModified": "2018-06-26T14:20:45.0214921",
"startDate": "2018-07-28T17:00:00",
"endDate": "2018-07-28T22:00:00",
"venue": {
"id": 0,
"name": "Giba Gorge Mountain Bike Park",
"addressLine1": "110 Stockville Road",
"addressLine2": "",
"latitude": -29.8276051,
"longitude": 30.781735700000013
},
"locality": {
"levelOne": "South Africa",
"levelTwo": "KwaZulu-Natal",
"levelThree": "Clifton Canyon"
},
"organiser": {
"id": 0,
"name": "Ultra Glow SA ",
"phone": "0822603351",
"mobile": "0828927837",
"facebookUrl": "",
"twitterHandle": "",
"hashTag": "UGMOVIES",
"organiserPageUrl": "some url"
},
"categories": [
{
"id": 3,
"name": "Film & Media"
},
{
"id": 12,
"name": "Food & Drink"
}
],
"tickets": [
{
"id": 98655,
"name": "ADULT TICKET",
"soldOut": false,
"provisionallySoldOut": false,
"price": 100,
"salesStart": "2018-06-26T11:52:00",
"salesEnd": "2018-07-28T17:00:00",
"description": "",
"donation": false,
"vendorTicket": false
},
{
"id": 98656,
"name": "UNDER 12",
"soldOut": false,
"provisionallySoldOut": false,
"price": 80,
"salesStart": "2018-06-26T11:53:00",
"salesEnd": "2018-07-28T17:00:00",
"description": "",
"donation": false,
"vendorTicket": false
}
],
"schedules": [
],
"refundFeePayableBy": 0
},
{
"id": 51681,
"name": "ULTRA GLOW COLOUR CRUZ # RIETVLEI ZOO FARM",
"url": "some url",
"imageUrl": "some path",
"dateCreated": "2018-06-26T12:12:07.3",
"lastModified": "2018-06-28T15:22:24.1579751",
"startDate": "2018-08-12T10:00:00",
"endDate": "2018-08-12T14:00:00",
"venue": {
"id": 0,
"name": "Rietvlei Zoo Farm",
"addressLine1": "101 Swartkoppies Road",
"addressLine2": "",
"latitude": -26.3117147,
"longitude": 28.07989120000002
},
"locality": {
"levelOne": "South Africa",
"levelTwo": "Gauteng",
"levelThree": "Johannesburg South"
},
"organiser": {
"id": 0,
"name": " Ultra Glow South Africa",
"phone": "0822603351",
"mobile": "0828927837",
"facebookUrl": "",
"twitterHandle": "",
"hashTag": "",
"organiserPageUrl": "some url"
},
"categories": [
{
"id": 60,
"name": "Trail Running"
},
{
"id": 5,
"name": "Sports & Fitness"
}
],
"tickets": [
{
"id": 98735,
"name": "ADULT EARLY BIRD",
"soldOut": false,
"provisionallySoldOut": false,
"price": 150,
"salesStart": "2018-06-26T12:47:00",
"salesEnd": "2018-08-12T10:00:00",
"description": "",
"donation": false,
"vendorTicket": false
},
{
"id": 98736,
"name": "UNDER 12 - EARLY BIRD",
"soldOut": false,
"provisionallySoldOut": false,
"price": 120,
"salesStart": "2018-06-26T12:47:00",
"salesEnd": "2018-08-12T10:00:00",
"description": "",
"donation": false,
"vendorTicket": false
}
],
"schedules": [
],
"refundFeePayableBy": 0
}
],
"pageSize": 10,
"pages": 1,
"records": 2,
"extras": null,
"message": null,
"statusCode": 0
}
i have tried the following code to insert the relevant datas into database
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
$n= sizeof($results);
for($i=0;$i<$n;$i++){
$row=$results[$i];
foreach($row['tickets'] as $key => $value){
$sql="INSERT into
event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price)
VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated"]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";
mysqli_query($connect,$sql);
}
}
echo "events data inserted";
?>
This enters the respective datas into my database but because of the nested array tickets with respective keys name and price the same events are being posted twice into my database like MOVIES AT THE PARK # GIBA GORGE for price 100 is one one row and MOVIES AT THE PARK # GIBA GORGE for price 80 on another row ... I have to display these datas in future as part of one event name with their the ticket type and price as a table... do you have any idea on any other way i can make it better, instead of having two rows for same events?
Thanks in advance
for those who have been suggesting me not to use for and foreach loop this is my update code after removing for loop and a single foreach loop and it gives me an error of undefined index of name and price under tickets
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
foreach($results as $key => $result){
$sql="INSERT into `event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketName,price) VALUES('".$result["name"]."','".$result["url"]."','".$result["imageUrl"]."','".$result["dateCreated"]."','".$result["venue"]["name"]."','".$result["venue"]["addressLine1"]."','".$result["venue"]["addressLine2"]."','".$result["tickets"]["name"]."','".$result["tickets"]["price"]."')";`
mysqli_query($connect,$sql);
}
echo "events data inserted";
?>
hence i have further updated my code by using two foreach loops, one to ietrate through the top level array "results" and the other to iterate through the nested array "tickets"
<?php
$connect= mysqli_connect("localhost","root","","result");
$jsondata=file_get_contents("result.json");
$json= json_decode($jsondata,true);
$results=$json['results'];
foreach($results as $key => $result){
foreach($result["tickets"] as $k => $v){
$sql="INSERT into event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketName,price) VALUES('".$result["name"]."','".$result["url"]."','".$result["imageUrl"]."','".$result["dateCreated"]."','".$result["venue"]["name"]."','".$result["venue"]["addressLine1"]."','".$result["venue"]["addressLine2"]."','".$v["name"]."','".$v["price"]."')";`
mysqli_query($connect,$sql);
}
}
echo "events data inserted";
?>
that iterates through the nested array so there is nothing wrong in my code now the only problem is i am getting 2 events on my table because of two ticket types adult and children in "tickets" array
so as per many suggestions here i need to create two separate tables for events and tickets i would appreciate if anyone can tell me that how do iconnect these two tables to be able to show the information of my events in html with ticket type and price shown in html table tag thanks in advance

The main reason that is happening is look at the below code :
$row=$results[$i];
foreach($row['tickets'] as $key => $value){
$sql="INSERT into event(name,url,imageUrl,dateCreated,eventName,addressLine1,addressLine2,ticketNa me,price) VALUES('".$row["name"]."','".$row["url"]."','".$row["imageUrl"]."','".$row["dateCreated]."','".$row["venue"]["name"]."','".$row["venue"]["addressLine1"]."','".$row["venue"]["addressLine2"]."','".$value["name"]."','".$value["price"]."')";
mysqli_query($connect,$sql);
}
The $row contains your one main entry and $row['tickets'] contains 2 entries and you are using the $row main contents inside the loop for tickets. That is the reason you are getting 2 entries. The best way to cope this is to use a single foreach loop instead of using a for and a foreach.
EDIT:
Actually I would like to suggest to normalize your table by breaking this into 2 tables, one for storing event information and the other for using the ticket information. See the structure below:
event(id,name,url,imageUrl,addressLine1,addressLine2,dateCreated);
event_tickets(id,event_id,ticketName,price,dateCreated);
This will help you maintain the information easily. Also you can modify the code to something like this :
$sql="INSERT into event(name,url,imageUrl,addressLine1,addressLine,2dateCreated) VALUES ('".$row['name']."','".$row['url']."','".$row['imageUrl']."','".$row['venue']['addressLine1']."','".$row['venue']['addressLine2']."','".date('Y-m-d h:i:s')."');"
mysqli_query($connect, $sql);
$event_id = mysqli_insert_id($connect);
And then you can use a foreach to insert the ticket information in the event_tickets table.
Hope this helps

it's because you're using a foreach within a for. You just want a foreach:
foreach ($multiArray as $key => $singleArray) {
//rest of code, replacing $row with $singleArray['key']. E.g. $singleArray['id']
}
update after seeing OP update:
so you would do:
foreach ($results as $row) {
foreach ($row['tickets'] as $ticket) {
//sql
}
}
this should allow you to use $ticket['key'] in your SQL - though I do suggest switch to PDO prepared statements to protect yourself from SQL injection.
Also as other suggested, separating tickets into its own table would be highly advantageous to you.

Related

How to get a particular string from and api response?

I have been on a little project of mine now i want to find imdb_id using tmdb_id so for that I have been trying to use the API.
https://api.themoviedb.org/3/tv/67026?api_key=myapikey&append_to_response=external_ids
which brings up the results like this
{
"backdrop_path": "/hcFbIbDzsB9aSSw9VkSGFEl5sGO.jpg",
"created_by": [{
"id": 230174,
"credit_id": "577eb8e5c3a368694a0027ac",
"name": "David Guggenheim",
"gender": 2,
"profile_path": "/hqSydaadHO6EsBIn3BQEzzfxNUY.jpg"
}],
"episode_run_time": [42],
"first_air_date": "2016-09-21",
"genres": [{
"id": 18,
"name": "Drama"
}, {
"id": 10768,
"name": "War & Politics"
}],
"homepage": "https://www.netflix.com/title/80113647",
"id": 67026,
"in_production": false,
"languages": ["en"],
"last_air_date": "2019-06-07",
"last_episode_to_air": {
"air_date": "2019-06-07",
"episode_number": 10,
"id": 1809432,
"name": "#truthorconsequences",
"overview": "On election day, Kirkman turns to his therapist to assuage his conscience about the events -- and his own decisions -- of the momentous prior 36 hours.",
"production_code": "",
"season_number": 3,
"show_id": 67026,
"still_path": "/cpy3uV100RyZuvJN535JLTrj4Nz.jpg",
"vote_average": 7.0,
"vote_count": 1
},
"name": "Designated Survivor",
"next_episode_to_air": null,
"networks": [{
"name": "ABC",
"id": 2,
"logo_path": "/ndAvF4JLsliGreX87jAc9GdjmJY.png",
"origin_country": "US"
}, {
"name": "Netflix",
"id": 213,
"logo_path": "/wwemzKWzjKYJFfCeiB57q3r4Bcm.png",
"origin_country": ""
}],
"number_of_episodes": 53,
"number_of_seasons": 3,
"origin_country": ["US"],
"original_language": "en",
"original_name": "Designated Survivor",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"popularity": 30.031,
"poster_path": "/5R125JAIh1N38pzHp2dRsBpOVNY.jpg",
"production_companies": [{
"id": 28788,
"logo_path": null,
"name": "Genre Films",
"origin_country": "US"
}, {
"id": 19366,
"logo_path": "/vOH8dyQhLK01pg5fYkgiS31jlFm.png",
"name": "ABC Studios",
"origin_country": "US"
}, {
"id": 78984,
"logo_path": null,
"name": "Entertainment 360",
"origin_country": "US"
}],
"seasons": [{
"air_date": "2016-09-20",
"episode_count": 21,
"id": 78328,
"name": "Season 1",
"overview": "Tom Kirkman, a low-level cabinet member is suddenly appointed President of the United States after a catastrophic attack during the State of the Union kills everyone above him in the Presidential line of succession.",
"poster_path": "/1QHlD6z9FnXuuTDVLJnjrtLfVyq.jpg",
"season_number": 1
}, {
"air_date": "2017-09-27",
"episode_count": 22,
"id": 91130,
"name": "Season 2",
"overview": "",
"poster_path": "/z4hdj8cYyqCO9lVBOGm6YZsnMho.jpg",
"season_number": 2
}, {
"air_date": "2019-06-07",
"episode_count": 10,
"id": 122914,
"name": "Season 3",
"overview": "",
"poster_path": "/wn310FWQhjjpHbqsMRBcXr28EHc.jpg",
"season_number": 3
}],
"status": "Canceled",
"type": "Scripted",
"vote_average": 7.2,
"vote_count": 408,
"external_ids": {
"imdb_id": "tt5296406",
"freebase_mid": null,
"freebase_id": null,
"tvdb_id": 311876,
"tvrage_id": 51115,
"facebook_id": "DesignatedSurvivor",
"instagram_id": "designatedsurvivor",
"twitter_id": "DesignatedNFLX"
}
}
So now if I want to get just the IMDb_ID form the external_ids then what code should i use in PHP and store it in a variable.
Thank you very much in advance.
use the json_decode method to treat JSON like a PHP object
$data = 'your JSON object';//raw data as string in $data
$decoded = json_decode($data);//decoded data as PHP object
echo $decoded->external_ids->imdb_id; //access any property you like
hope this helps!!!

PHP - Retrieve JSON data and values [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];

PHP - Most efficient way to filter two arrays

I have a question on what is the most performant way to filter two arrays of objects. I have two arrays of products from different systems and i want to work out which products have been removed from one array and then return the products that have been removed.
See the current function i have below which i know is super slow.
public function checkRemove($externalProducts, $localProducts){
//Push all the SKU codes from feed to an array();
$arr = [];
foreach ($externalProducts->products as $product) {
if($product->StockNumber != null){
array_push($arr, $product->StockNumber);
}
}
//Loop through the local products
$productsRemove = [];
foreach ($localProducts->products as $key => $localProduct) {
if(in_array($localProduct->sku, $arr)){
}else{
array_push($productsRemove, $localProduct);
}
}
return $productsRemove;
}
$externalProducts = {
"Filter": {
"Title": "All Products"
},
"Products": [{
"Type": "Jacket",
"Price": 75,
"ExpiryDate": "2018-06-30",
"StockNumber": "180220/003",
"Created": "2018-02-20 12:24:06",
"Modified": "2018-05-30 02:00:23"
},
{
"Type": "Jeans",
"Price": 150,
"ExpiryDate": "2018-06-30",
"StockNumber": "180221/004",
"Created": "2017-08-10 15:11:44",
"Modified": "2018-05-30 02:00:22"
},
{
"Type": "Jacket",
"Price": 240,
"ExpiryDate": "2018-06-30",
"StockNumber": "150804/012",
"Created": "2015-08-04 17:03:42",
"Modified": "2018-05-30 02:00:22"
}
]
}
$internalProducts = "localProducts": [{
"title": "Fur Coat",
"id": 16526,
"created_at": "2018-05-17T10:15:45Z",
"updated_at": "2018-05-17T10:15:45Z",
"sku": "180514/001",
"price": "75.00",
"regular_price": "75.00",
"categories": [
"Jackets",
],
},
{
"title": "Ripped Jeans",
"id": 16527,
"created_at": "2018-05-17T10:15:45Z",
"updated_at": "2018-05-17T10:15:45Z",
"sku": "180221/004",
"price": "150.00",
"regular_price": "150.00",
"categories": [
"Jeans",
],
},
{
"title": "Leather Jacket",
"id": 16528,
"created_at": "2018-05-17T10:15:45Z",
"updated_at": "2018-05-17T10:15:45Z",
"sku": "150804/012",
"price": "240.00",
"regular_price": "240.00",
"categories": [
"Jackets",
],
}
]
Take a look at array_filter
You can provide a callback function which will be run for each element in the array. If the callback function returns true, the current value from the array is returned in the result array.
You still have to iterate over one array at least. It is $localProducts. So, for $localProducts there're no improvements. But you can improve $externalProducts - add a special method (if you can) that will return StockNumbers only. More effective will be if StockNumbers will be of structure as:
[
'stocknumber1' => true,
'stocknumber2' => true,
'stocknumber3' => true,
'stocknumber4' => true,
'stocknumber5' => true,
]
This will improve your search, as checking isset($StockNumbers['stocknumber4']) is faster than in_array or array_search.
If you can't change structure of $externalProducts->products, than build array of stock numbers in a loop:
public function checkRemove($externalProducts, $localProducts){
//Push all the SKU codes from feed to an array();
$arr = [];
foreach ($externalProducts->products as $product) {
if ($product->StockNumber != null){
// Again I add sku as key, not as value
$arr[$product->StockNumber] = true;
}
}
//Loop through the local products
$productsRemove = [];
foreach ($localProducts->products as $localProduct) {
// check with `isset` is faster
if (isset($arr[$localProduct->sku])) {
array_push($productsRemove, $localProduct);
}
}
return $productsRemove;
}

Parsing a JSON file with multiple levels in a MySQL database

I've some trouble with parsing a JSON file into a MySQL database. It's an export of some Facebookstats.
Because I've multiple export of multiple pages, it's important that I've the corresponding ID in the database.
The JSONfile (or cURL from Facebook) looks like this:
{
"data": [
{
"name": "impressions",
"period": "week",
"values": [
{
"value": 123456789,
"end_time": "2016-01-01T08:00:00+0000"
},
{
"value": 12345678,
"end_time": "2016-01-02T08:00:00+0000"
},
{
"value": 1234567,
"end_time": "2016-01-03T08:00:00+0000"
},
{
"value": 123456,
"end_time": "2016-01-04T08:00:00+0000"
},
{
"value": 12345,
"end_time": "2016-01-05T08:00:00+0000"
}
],
"title": "Weekly Impressions",
"description": "The number of impressions seen of any content associated with your Page. (Total Count)",
"id": "101010101010\/insights\/page_impressions\/week"
}
],
"paging": {
"previous": "1",
"next": "2"
}
}
I would, ideally, parse this data into a MySQL database that looks like this:
id value end_time
101010101010 123456789 2016-01-01T08:00:00+0000
101010101010 12345678 2016-01-02T08:00:00+0000
101010101010 1234567 2016-01-03T08:00:00+0000
101010101010 123456 2016-01-04T08:00:00+0000
101010101010 12345 2016-01-05T08:00:00+0000
I hope someone had some ideas :-)
Use json_decode(). Example:
$jsonString = '{
"data": [
{
"name": "impressions",
"period": "week",
"values": [
{
"value": 123456789,
"end_time": "2016-01-01T08:00:00+0000"
},
{
"value": 12345678,
"end_time": "2016-01-02T08:00:00+0000"
},
{
"value": 1234567,
"end_time": "2016-01-03T08:00:00+0000"
},
{
"value": 123456,
"end_time": "2016-01-04T08:00:00+0000"
},
{
"value": 12345,
"end_time": "2016-01-05T08:00:00+0000"
}
],
"title": "Weekly Impressions",
"description": "The number of impressions seen of any content associated with your Page. (Total Count)",
"id": "101010101010\/insights\/page_impressions\/week"
}
],
"paging": {
"previous": "1",
"next": "2"
}
}';
Then decode it to an associative array:
$assocData = json_decode($jsonString, true); //Setting second optional parameter to true makes it return an associative array.
Then access it however you want:
$data = $assocData['data'];

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