I am trying to get my head around how I can get the SKU's (and additionally the ID) from json results. I can do this when there are just one set of values called SKU but I have spent hours trying to understand how to do this when there are multiple.
Below is a sample of what my json returns
{
"variants": [
{
"id": 6852445,
"name": "Ikan VK7i 7\" LCD Monitor for Sony L with sun hood",
"sku": "VK7i-S-SHX7",
},
{
"id": 6852388,
"name": "ikan Flyweight DSLR",
"sku": "ELE-FLWDSLR",
},
{
"id": 6838367,
"name": "Atomos Sun Hood for Ninja/Ninja-2 including Double Adapter",
"sku": "AO-ATOMSUN001",
},
]
}
I currently have this code (I am a newbee). What I am trying to do is make the sku and the ID both variables but I am just hitting a brick wall. Currently I get
Warning: Invalid argument supplied for foreach() in /home/pearingc/public_html/returns/test2.php on line 15
<?php
$context = stream_context_create(array(
'http' => array(
'header' => "Authorization: Bearer *my token details* ")
)
);
$url = "http://api.tradegecko.com/variants/";
$data = file_get_contents($url, false, $context);
$json = json_decode($data, true);
$product = $json{'variant'}->{'sku'};
foreach ($product['sku'] as $sku) {
print $sku;
}
?>
Edit: This is what the var_dump($json); gives me
object(stdClass)#1 (2) { ["variants"]=> array(100) { [0]=> object(stdClass)#2 (42) { ["id"]=> int(6852445) ["created_at"]=> string(24) "2015-05-20T10:09:09.629Z" ["updated_at"]=> string(24) "2015-05-20T10:10:40.351Z" ["product_id"]=> int(1991122) ["default_ledger_account_id"]=> NULL ["buy_price"]=> string(5) "404.0" ["committed_stock"]=> string(1) "0" ["incoming_stock"]=> string(1) "0" ["composite"]=> bool(true) ["description"]=> NULL ["is_online"]=> bool(false) ["keep_selling"]=> bool(false) ["last_cost_price"]=> NULL ["manage_stock"]=> bool(true) ["max_online"]=> NULL ["moving_average_cost"]=> NULL ["name"]=> string(49) "Ikan VK7i 7" LCD Monitor for Sony L with sun hood" ["online_ordering"]=> bool(false) ["opt1"]=> NULL ["opt2"]=> NULL ["opt3"]=> NULL ["position"]=> int(6) ["product_name"]=> string(33) "ikan 7" HDMI Monitor W/ IPS Panel" ["product_status"]=> string(6) "active" ["product_type"]=> string(8) "Monitors" ["retail_price"]=> NULL ["sellable"]=> bool(true) ["sku"]=> string(11) "VK7i-S-SHX7" ["status"]=> string(6) "active" ["stock_on_hand"]=> string(1) "0" ["supplier_code"]=> NULL ["taxable"]=> bool(true) ["upc"]=> NULL ["weight"]=> NULL ["wholesale_price"]=> NULL ["image_ids"]=> array(0) { } ["variant_prices"]=> array(1) { [0]=> object(stdClass)#3 (2) { ["price_list_id"]=> string(3) "buy" ["value"]=> string(5) "404.0" } } ["locations"]=> array(1) { [0]=> object(stdClass)#4 (6) { ["location_id"]=> int(16377) ["stock_on_hand"]=> string(1) "0" ["committed"]=> string(1) "0" ["incoming"]=> NULL ["bin_location"]=> NULL ["reorder_point"]=> NULL } } ["prices"]=> object(stdClass)#5 (1) { ["buy"]=> string(5) "404.0" } ["stock_levels"]=> object(stdClass)#6 (1) { ["16377"]=> string(3) "0.0" } ["committed_stock_levels"]=> object(stdClass)#7 (1) { ["16377"]=> string(3) "0.0" } ["incoming_stock_levels"]=> object(stdClass)#8 (0) { } }
I think You have malformed JSON. Note: I removed commas after sku. Try this :
$data = '{
"variants": [
{
"id": 6852445,
"name": "Ikan VK7i 7\" LCD Monitor for Sony L with sun hood",
"sku": "VK7i-S-SHX7"
},
{
"id": 6852388,
"name": "ikan Flyweight DSLR",
"sku": "ELE-FLWDSLR"
},
{
"id": 6838367,
"name": "Atomos Sun Hood for Ninja/Ninja-2 including Double Adapter",
"sku": "AO-ATOMSUN001"
}
]
}';
And after that:
$json = json_decode($data);
foreach ($json->variants as $row) {
print $row->sku;
}
<?php
$json = '{
"variants": [
{
"id": 6852445,
"name": "Ikan VK7i 7\" LCD Monitor for Sony L with sun hood",
"sku": "VK7i-S-SHX7"
},
{
"id": 6852388,
"name": "ikan Flyweight DSLR",
"sku": "ELE-FLWDSLR"
},
{
"id": 6838367,
"name": "Atomos Sun Hood for Ninja/Ninja-2 including Double Adapter",
"sku": "AO-ATOMSUN001"
}
]
}';
foreach(json_decode($json,true)['variants'] as $item) {
echo $item['sku'] . "<br />";
}
?>
Condensed it a little bit.
Related
I'm having trouble sorting alphabetically an object returned by the json_decode function in PHP.
The object I've got is as follows:
object(stdClass)#9263 (1) {
["Activities"]=>
array(91) {
[0]=>
object(stdClass)#6116 (3) {
["Code"]=>
string(1) "5"
["NameFr"]=>
string(16) "Droit ju"
["NameNl"]=>
string(18) "Ger recht"
}
[1]=>
object(stdClass)#8582 (3) {
["Code"]=>
string(1) "1"
["NameFr"]=>
string(19) "Droit per"
["NameNl"]=>
string(13) "Pers recht"
}
[2]=>
object(stdClass)#8598 (3) {
["Code"]=>
string(5) "2"
["NameFr"]=>
string(11) "Droit ca"
["NameNl"]=>
string(14) "Ca recht"
}
...
I need to sort it using the "NameFr" property, alphabetically.
try usort
<?php
$data = '
{
"Activities": [
{
"Code": "5",
"NameFr": "Droit ju",
"NameNl": "Ger recht"
},
{
"Code": "1",
"NameFr": "Droit per",
"NameNl": "Pers recht"
},
{
"Code": "2",
"NameFr": "Droit ca",
"NameNl": "Ca recht"
}
]
}';
$data = json_decode($data, true);
usort($data["Activities"], function($a, $b) {
return $a['NameFr'] <=> $b['NameFr'];
});
print_r($data);
I am currently stuck in json formatting for php. I have given my outputted json below. What I need to do is to make the format of the current json to the desired one. I am missing the arrays in the JSON format. Can anyone help me on this.
My code to print the json output is below:
$menuHead=array();
$i=0;
foreach($res as $key => $value){
$i=$key+1;
//$menuHead[$i]['menuHead']=$value['category'];
if(isset($menuHead[$key]['menuHead'])){
if($menuHead[$key]['menuHead']==$value['category']){
$menuHead[$key]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$key]['data'][$i]['price']=$value['price'];
$menuHead[$key]['data'][$i]['description']=$value['description'];
$menuHead[$key]['data'][$i]['itemId']=$value['id'];
$menuHead[$key]['data'][$i]['customizable']=$value['customizable'];
}else{
$menuHead[$i]['menuHead']=$value['category'];
$menuHead[$i]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$i]['data'][$i]['price']=$value['price'];
$menuHead[$i]['data'][$i]['description']=$value['description'];
$menuHead[$i]['data'][$i]['itemId']=$value['id'];
$menuHead[$i]['data'][$i]['customizable']=$value['customizable'];
}
}else{
$menuHead[$i]['menuHead']=$value['category'];
$menuHead[$i]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$i]['data'][$i]['price']=$value['price'];
$menuHead[$i]['data'][$i]['description']=$value['description'];
$menuHead[$i]['data'][$i]['itemId']=$value['id'];
$menuHead[$i]['data'][$i]['customizable']=$value['customizable'];
}
}
$final['MenuList']=$menuHead;
echo json_encode($final);
Current format:
{
"MenuList": {
"1": {
"menuHead": "Main Course",
"data": {
"1": {
"itemName": "Chicken Thai Curry",
"price": "599",
"description": "",
"itemId": "67",
"customizable": "1"
}
}
},
"2": {
"menuHead": "Refreshments",
"data": {
"2": {
"itemName": "Kingfisher Premium",
"price": "999",
"description": "Kingfisher beer",
"itemId": "69",
"customizable": "1"
},
"3": {
"itemName": "Mocktail",
"price": "999",
"description": "",
"itemId": "68",
"customizable": "1"
}
}
},
"4": {
"menuHead": "Rice biriyani",
"data": {
"4": {
"itemName": "Dal makni risotto",
"price": "499",
"description": "Dal makhni risotto",
"itemId": "66",
"customizable": "1"
}
}
}
}
}
Desired Format:
{
"menuList": [
{
"menuHead": "In Steamer (Momos)",
"data": [
{
"itemName": "Tandoori Momo",
"description": "",
"price": "150",
"itemId": "16",
"customizable": "0"
},
{
"itemName": "Fried Momo Pork",
"price": "100",
"description": "",
"itemId": "15",
"customizable": "0"
}
]
},
{
"itemName": "Rice and Noodles",
"data": [
{
"sub_category": "Tandoori Momo",
"description": "",
"price": "150",
"itemId": "16",
"customizable": "0"
},
{
"itemName": "Fried Momo Pork",
"price": "100",
"description": "",
"itemId": "15",
"customizable": "0"
}
]
}
]
}
Raw response is below:
array(4) { [0]=> array(7) { ["id"]=> string(2) "67" ["restaurant_id"]=> string(1) "5" ["category"]=> string(11) "Main Course" ["sub_category"]=> string(18) "Chicken Thai Curry" ["price"]=> string(3) "599" ["description"]=> string(0) "" ["customizable"]=> string(1) "1" } [1]=> array(7) { ["id"]=> string(2) "69" ["restaurant_id"]=> string(1) "5" ["category"]=> string(12) "Refreshments" ["sub_category"]=> string(18) "Kingfisher Premium" ["price"]=> string(3) "999" ["description"]=> string(15) "Kingfisher beer" ["customizable"]=> string(1) "1" } [2]=> array(7) { ["id"]=> string(2) "68" ["restaurant_id"]=> string(1) "5" ["category"]=> string(12) "Refreshments" ["sub_category"]=> string(8) "Mocktail" ["price"]=> string(3) "999" ["description"]=> string(0) "" ["customizable"]=> string(1) "1" } [3]=> array(7) { ["id"]=> string(2) "66" ["restaurant_id"]=> string(1) "5" ["category"]=> string(13) "Rice biriyani" ["sub_category"]=> string(17) "Dal makni risotto" ["price"]=> string(3) "499" ["description"]=> string(18) "Dal makhni risotto" ["customizable"]=> string(1) "1" } }
If you want a javascript compatible array, the index must start at 0. The easiest way to do that, is to use array_values():
$final['MenuList'] = array_values($menuHead);
The problem is that when your adding the data items, you need to add them without specific keys, as you add them with $i as in...
$menuHead[$key]['data'][$i]['itemName']=$value['sub_category'];
This will stop them being a normal array as you want it to be. For json_encode() an array must start at 0 and be sequential for it to be an array.
Instead create them in one go and add them to the end of the existing data using []...
$menuHead[$key]['data'][] = ['itemName' =>$value['sub_category'],
'price'=> $value['price'],
'description'=>$value['description'],
'itemId'=>$value['id'],
'customizable'=>$value['customizable']];
This needs to be done with each set of similar code, which includes the overall array itself, this can be done using
$final['MenuList'] = array_values($menuHead);
To try and fix the data you already have, which means no changes except adding the following code...
foreach ( $menuHead as $menu ) {
$menu['data'] = array_values($menu['data']);
}
$final['MenuList'] = array_values($menuHead);
Use array_values();
I fixed your code, it should work
$menuHead=array();
$i=0;
foreach($res as $key => $value){
$i=$key+1;
//$menuHead[$i]['menuHead']=$value['category'];
if(isset($menuHead[$key]['menuHead'])){
if($menuHead[$key]['menuHead']==$value['category']){
$menuHead[$key]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$key]['data'][$i]['price']=$value['price'];
$menuHead[$key]['data'][$i]['description']=$value['description'];
$menuHead[$key]['data'][$i]['itemId']=$value['id'];
$menuHead[$key]['data'][$i]['customizable']=$value['customizable'];
}else{
$menuHead[$i]['menuHead']=$value['category'];
$menuHead[$i]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$i]['data'][$i]['price']=$value['price'];
$menuHead[$i]['data'][$i]['description']=$value['description'];
$menuHead[$i]['data'][$i]['itemId']=$value['id'];
$menuHead[$i]['data'][$i]['customizable']=$value['customizable'];
}
}else{
$menuHead[$i]['menuHead']=$value['category'];
$menuHead[$i]['data'][$i]['itemName']=$value['sub_category'];
$menuHead[$i]['data'][$i]['price']=$value['price'];
$menuHead[$i]['data'][$i]['description']=$value['description'];
$menuHead[$i]['data'][$i]['itemId']=$value['id'];
$menuHead[$i]['data'][$i]['customizable']=$value['customizable'];
}
}
// i'am use array_values()
$final['MenuList']= array_values($menuHead);
echo json_encode($final);
i am using abraham/twitteroauth for twitter feed. Everything works normal as expected, just cannot get [unwound] object as explained on twitter for developers website.
object(stdClass)#7 (25) {
["entities"]=>
object(stdClass)#16 (4) {
["urls"]=>
array(1) {
[0]=>
object(stdClass)#17 (4) {
["url"]=>
string(23) "link"
["expanded_url"]=>
string(73) "https://www.invisionapp.com/blog/7-ted-talks-every-designer-should-watch/"
["display_url"]=>
string(33) "invisionapp.com/blog/7-ted-tal…"
["indices"]=>
array(2) {
[0]=>
int(46)
[1]=>
int(69)
}
}
}
}
In Twitter for developers website i see unwound. But in my var_dump i cant find.
{"urls": [
{
"url": "link",
"expanded_url": "link",
"display_url": "link",
"unwound": {
"url": "https://www.youtube.com/watch?v=oHg5SJYRHA0",
"status": 200,
"title": "RickRoll'D",
"description": "http://www.facebook.com/rickroll548 As long as trolls are still trolling, the Rick will never stop rolling."
},
"indices": [
62,
85
]
}
]
}
Maybe have some ideas ? Appreciate for help!:)
I used stripe to return a Customer Object. I want to extract the bank account ID and save it in a database for later use. What is the proper syntax to access the array properly?
Here is what I have tried:
$bank_account=$customer->lastResponse['json']['sources']['data'][0]['id'];
I was told to try:
$bank_account=$customer->bank_accounts->data[0]['id'];
But that came up null as well...
Im not sure how to work with the object or what the right way to do this is.
I need the bank_account_id
This is what the var_dump($customer) looks like after some formatting and removing information that is not pertinent. I think I can either use a JSON decode or access the array called 'json' i dont know the proper syntax for either of those solutions. Help please (:
object(Stripe\Customer)#3572 (6)
{
["_opts":protected]=> object(Stripe\Util\RequestOptions)#3576 (2) { ["headers"]=> array(1) { ["Stripe-Account"]=> string(21) "acct_1BNn74AprSj6yALS" } ["apiKey"]=> string(32) "secretkey" }
["_values":protected]=> array(15) {//Removed For brevity}
["_unsavedValues":protected]=> object(Stripe\Util\Set)#3590 (1) { ["_elts":"Stripe\Util\Set":private]=> array(0) { } } ["_transientValues":protected]=> object(Stripe\Util\Set)#3602 (1) { ["_elts":"Stripe\Util\Set":private]=> array(0) { } } ["_retrieveOptions":protected]=> array(0) { }
["_lastResponse":protected]=>
object(Stripe\ApiResponse)#3714 (4)
{
["headers"]=> array(15) { //Removed for brevity}
// Json
["body"]=> string(1148) "{
"id": "cus_BoJOjFghfV7mmq", "object": "customer", "account_balance": 0, "created": 1511290036, "currency": null, "default_source": "bank_account_id", "delinquent": false, "description": "Name", "discount": null, "email": null, "livemode": true, "metadata": {}, "shipping": null, "sources": { "object": "list", "data": [ { "id": "bank_account_id", "object": "bank_account", "account_holder_name": "Daniel Taylor", "account_holder_type": "individual", "bank_name": "Bank Name", "country": "US", "currency": "usd", "customer": "cus_id", "fingerprint": "info", "last4": "last four of account", "metadata": {}, "routing_number": "routing number", "status": "new" } ], "has_more": false, "total_count": 1, "url": "/v1/customers/cus_BoJOjFghfV7mmq/sources" }, "subscriptions": { "object": "list", "data": [], "has_more": false, "total_count": 0, "url": "/v1/customers/cus_BoJOjFghfV7mmq/subscriptions" }
} "
["json"]=> array(15)
{
["id"]=> string(18) "cus_id"
["object"]=> string(8) "customer"
["account_balance"]=> int(0)
["created"]=> int(1511290036)
["currency"]=> NULL
["default_source"]=> string(27) "bank_account_id"
["delinquent"]=> bool(false)
["description"]=> string(13) "Name"
["discount"]=> NULL
["email"]=> NULL ["livemode"]=> bool(true)
["metadata"]=> array(0) { }
["shipping"]=> NULL
["sources"]=> array(5)
{
["object"]=> string(4) "list"
["data"]=> array(1)
{
[0]=> array(13)
{
["id"]=> string(27) "bank_account_id" ["object"]=> string(12) "bank_account"
["account_holder_name"]=> string(13) "name"
["account_holder_type"]=> string(10) "individual"
["bank_name"]=> string(26) "Bank Name"
["country"]=> string(2) "US" ["currency"]=> string(3) "usd"
["customer"]=> string(18) "cus_ID"
["fingerprint"]=> string(16) "fingerprint"
["last4"]=> string(4) "lastfour" ["metadata"]=> array(0) { }
["routing_number"]=> string(9) "routenumber"
["status"]=> string(3) "new"
}
}
["has_more"]=> bool(false)
["total_count"]=> int(1)
["url"]=> string(40) "/v1/customers/cus_BoJOjFghfV7mmq/sources"
}
["subscriptions"]=> array(5) { ["object"]=> string(4) "list" ["data"]=> array(0) { } ["has_more"]=> bool(false) ["total_count"]=> int(0) ["url"]=> string(46) "/v1/customers/cus_id/subscriptions" }
}
["code"]=> int(200)
}
}
I think it should be:
$bank_account = $customer->sources->data[0]->id
If the customer has multiple fund sources, you may need to loop through the data array to find the one you want. $customer->sources->data[$i]->object will be "bank_account" for the source you want.
Pretty sure there is a getter in there. You can just use the properties you would expect on the object.
Example:
$customer_id = $customer->id;
$bank_account_id = $customer->sources->data[0]->id;
Below is the result and I want to remove duplicate from the array
I tried using this code: $login_data1['items'] = array_values(array_map("unserialize", array_unique(array_map("serialize", $login_data1['items']))));
{
"items": [
{
"id": "2",
"tags": [
{
"name": "Microsoft"
}
],
"type": "manual",
},
{
"id": "1",
"tags": [
{
"name": "Snow Leopard"
}
],
"type": "faq"
},
{
"id": "2",
"tags": [
{
"name": "Microsoft"
}
],
"type": "manual"
}
],
}
I tried using $login_data1['items'] = array_unique($login_data1['items'] ,SORT_REGULAR); but this adds serial numbers at the each json response
Try as using array_unique
$json = '{
"items": [
{
"id": "2",
"tags": [
{
"name": "Microsoft"
}
],
"type": "manual"
},
{
"id": "1",
"tags": [
{
"name": "Snow Leopard"
}
],
"type": "faq"
},
{
"id": "2",
"tags": [
{
"name": "Microsoft"
}
],
"type": "manual"
}
]
}';
foreach(json_decode($json, true) as $key => $value){
$input = array_unique($value,SORT_REGULAR);
}
If its an array then simply use
array_unique($login_data['items'],SORT_REGULAR);
Fiddle
array_unique works perfectly if you pass a multidimensional array.
$login_data1['items'] = array_unique($login_data1['items'], SORT_REGULAR);
It doesn't work with your json because it's an array of object. Infact:
$array = json_decode($json);
var_dump($array);
returns:
object(stdClass)#1 (1) {
["items"]=>
array(3) {
[0]=>
object(stdClass)#2 (3) {
["id"]=>
string(1) "2"
["tags"]=>
array(1) {
[0]=>
object(stdClass)#3 (1) {
["name"]=>
string(9) "Microsoft"
}
}
["type"]=>
string(6) "manual"
}
[1]=>
object(stdClass)#4 (3) {
["id"]=>
string(1) "1"
["tags"]=>
array(1) {
[0]=>
object(stdClass)#5 (1) {
["name"]=>
string(12) "Snow Leopard"
}
}
["type"]=>
string(3) "faq"
}
[2]=>
object(stdClass)#6 (3) {
["id"]=>
string(1) "2"
["tags"]=>
array(1) {
[0]=>
object(stdClass)#7 (1) {
["name"]=>
string(9) "Microsoft"
}
}
["type"]=>
string(6) "manual"
}
}
}
Your json should look like this:
{
"items": [
{
"id": "2",
"tags": {
"name": "Microsoft"
},
"type": "manual"
},
{
"id": "1",
"tags": {
"name": "Snow Leopard"
},
"type": "faq"
},
{
"id": "2",
"tags": {
"name": "Microsoft"
},
"type": "manual"
},
{
"id": "2",
"tags": {
"name": "Microsoft"
},
"type": "manual"
}
]
}
And now:
$array = json_decode($json);
var_dump($array);
returns:
array(1) {
["items"]=>
array(4) {
[0]=>
array(3) {
["id"]=>
string(1) "2"
["tags"]=>
array(1) {
["name"]=>
string(9) "Microsoft"
}
["type"]=>
string(6) "manual"
}
[1]=>
array(3) {
["id"]=>
string(1) "1"
["tags"]=>
array(1) {
["name"]=>
string(12) "Snow Leopard"
}
["type"]=>
string(3) "faq"
}
[2]=>
array(3) {
["id"]=>
string(1) "2"
["tags"]=>
array(1) {
["name"]=>
string(9) "Microsoft"
}
["type"]=>
string(6) "manual"
}
[3]=>
array(3) {
["id"]=>
string(1) "2"
["tags"]=>
array(1) {
["name"]=>
string(9) "Microsoft"
}
["type"]=>
string(6) "manual"
}
}
}
And array_unique works.
I got the solution for this.
$login_data1['items'] =array_values(array_unique($login_data1['items'] ,SORT_REGULAR));
Try array_value and array_unique together and serial number will be removed!
$login_data1['items'] =array_values(array_unique($login_data1['items'] ,SORT_REGULAR));