I have an array like below.is there any way or one line code to empty all values inside array without foreach loop.
$array=json_decode('{
"client": "4",
"gateWay": "1",
"store": "store.shop.com",
"valid": "true",
"po": 34535,
"additionalPO": 23423,
"customerNotes": "",
"orderItems": [
{
"item": "123",
"quantity": 10,
"supplierLotNo": "",
"customsValue": "",
"customsDescription": "",
"hsCode": ""
},
{
"item": "345",
"quantity": 50
}
],
"shippingInfos": [
{
"address": {
"city": "Chennai",
"country": "India",
"postalCode": "86715",
"state": "TN",
"streetAddress1": "6971 North Street",
"streetAddress2": null
},
"contact": {
"company": null,
"email": "info#store.com",
"firstName": "test",
"lastName": "test",
"phoneNo": null
},
"ServiceId": "3",
"thirdPartyAccountNo": "",
"signatureConfirmation": false,
"saturdayDelivery": false
}
]
}',true);
The expected output should be I need empty string for string values,0 for integer values.
any help would be greatly appreciated.
You can do it with array_walk, assuming boolean is set to be NULL, here is the code.
Code
<?php
$array=json_decode('{
"client": "4",
"gateWay": "1",
"store": "store.shop.com",
"valid": "true",
"po": 34535,
"additionalPO": 23423,
"customerNotes": "",
"orderItems": [
{
"item": "123",
"quantity": 10,
"supplierLotNo": "",
"customsValue": "",
"customsDescription": "",
"hsCode": ""
},
{
"item": "345",
"quantity": 50
}
],
"shippingInfos": [
{
"address": {
"city": "Chennai",
"country": "India",
"postalCode": "86715",
"state": "TN",
"streetAddress1": "6971 North Street",
"streetAddress2": null
},
"contact": {
"company": null,
"email": "info#store.com",
"firstName": "test",
"lastName": "test",
"phoneNo": null
},
"ServiceId": "3",
"thirdPartyAccountNo": "",
"signatureConfirmation": false,
"saturdayDelivery": false
}
]
}',true);
($fx = function (&$in) use (&$fx) { is_array($in) ? array_walk($in, $fx) : ($in = is_string($in) ? "" : (is_int($in) ? 0 : NULL));})($array);
var_dump($array);
Output
array(9) {
["client"]=>
string(0) ""
["gateWay"]=>
string(0) ""
["store"]=>
string(0) ""
["valid"]=>
string(0) ""
["po"]=>
int(0)
["additionalPO"]=>
int(0)
["customerNotes"]=>
string(0) ""
["orderItems"]=>
array(2) {
[0]=>
array(6) {
["item"]=>
string(0) ""
["quantity"]=>
int(0)
["supplierLotNo"]=>
string(0) ""
["customsValue"]=>
string(0) ""
["customsDescription"]=>
string(0) ""
["hsCode"]=>
string(0) ""
}
[1]=>
array(2) {
["item"]=>
string(0) ""
["quantity"]=>
int(0)
}
}
["shippingInfos"]=>
array(1) {
[0]=>
array(6) {
["address"]=>
array(6) {
["city"]=>
string(0) ""
["country"]=>
string(0) ""
["postalCode"]=>
string(0) ""
["state"]=>
string(0) ""
["streetAddress1"]=>
string(0) ""
["streetAddress2"]=>
NULL
}
["contact"]=>
array(5) {
["company"]=>
NULL
["email"]=>
string(0) ""
["firstName"]=>
string(0) ""
["lastName"]=>
string(0) ""
["phoneNo"]=>
NULL
}
["ServiceId"]=>
string(0) ""
["thirdPartyAccountNo"]=>
string(0) ""
["signatureConfirmation"]=>
NULL
["saturdayDelivery"]=>
NULL
}
}
}
Related
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 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));
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.
I make a JSON call using an API and get the following, which seems to be correctly formatted JSON:
{
"pagination": {},
"meta": {
"code": 200
},
"data": [
{
"tags": [],
"location": {
"latitude": 37.42833,
"name": "Stanford University",
"longitude": -122.1668,
"id": 10138861
},
"comments": {
"count": 0,
"data": []
},
"filter": "Rise",
"created_time": "1331327429",
"link": "http://instagr.am/p/H91ykZpqUW/",
"likes": {
"count": 3,
"data": [
{
"username": "razzles39",
"profile_picture": "http://images.instagram.com/profiles/profile_14316422_75sq_1322705511.jpg",
"id": "14316422",
"full_name": "razzles39"
},
{
"username": "mscaliti",
"profile_picture": "http://images.instagram.com/profiles/profile_10827166_75sq_1330704753.jpg",
"id": "10827166",
"full_name": "mscaliti"
},
{
"username": "mariecox",
"profile_picture": "http://images.instagram.com/profiles/profile_3987147_75sq_1324863102.jpg",
"id": "3987147",
"full_name": "Marie Cox"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_7.jpg",
"width": 612,
"height": 612
}
},
"caption": {
"created_time": "1331327500",
"text": "Chillin with Brady at Stanford",
"from": {
"username": "nicolelainefox",
"profile_picture": "http://images.instagram.com/profiles/anonymousUser.jpg",
"id": "17982472",
"full_name": "nicolelainefox"
},
"id": "143507936292283648"
},
"type": "image",
"id": "143507334669706518_17982472",
"user": {
"username": "nicolelainefox",
"website": "",
"bio": "",
"profile_picture": "http://images.instagram.com/profiles/anonymousUser.jpg",
"full_name": "nicolelainefox",
"id": "17982472"
}
}
]
}
I then use json_decode in my PHP script to make it something I can manipulate, and this is the output of var_dump
object(stdClass)#1 (3) { ["pagination"]=> object(stdClass)#2 (0) { } ["meta"]=> object(stdClass)#3 (1) { ["code"]=> int(200) } ["data"]=> array(1) { [0]=> object(stdClass)#4 (12) { ["tags"]=> array(0) { } ["location"]=> object(stdClass)#5 (4) { ["latitude"]=> float(37.42833) ["name"]=> string(19) "Stanford University" ["longitude"]=> float(-122.1668) ["id"]=> int(10138861) } ["comments"]=> object(stdClass)#6 (2) { ["count"]=> int(0) ["data"]=> array(0) { } } ["filter"]=> string(4) "Rise" ["created_time"]=> string(10) "1331327429" ["link"]=> string(31) "http://instagr.am/p/H91ykZpqUW/" ["likes"]=> object(stdClass)#7 (2) { ["count"]=> int(3) ["data"]=> array(3) { [0]=> object(stdClass)#8 (4) { ["username"]=> string(9) "razzles39" ["profile_picture"]=> string(73) "http://images.instagram.com/profiles/profile_14316422_75sq_1322705511.jpg" ["id"]=> string(8) "14316422" ["full_name"]=> string(9) "razzles39" } [1]=> object(stdClass)#9 (4) { ["username"]=> string(8) "mscaliti" ["profile_picture"]=> string(73) "http://images.instagram.com/profiles/profile_10827166_75sq_1330704753.jpg" ["id"]=> string(8) "10827166" ["full_name"]=> string(8) "mscaliti" } [2]=> object(stdClass)#10 (4) { ["username"]=> string(8) "mariecox" ["profile_picture"]=> string(72) "http://images.instagram.com/profiles/profile_3987147_75sq_1324863102.jpg" ["id"]=> string(7) "3987147" ["full_name"]=> string(9) "Marie Cox" } } } ["images"]=> object(stdClass)#11 (3) { ["low_resolution"]=> object(stdClass)#12 (3) { ["url"]=> string(79) "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_6.jpg" ["width"]=> int(306) ["height"]=> int(306) } ["thumbnail"]=> object(stdClass)#13 (3) { ["url"]=> string(79) "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_5.jpg" ["width"]=> int(150) ["height"]=> int(150) } ["standard_resolution"]=> object(stdClass)#14 (3) { ["url"]=> string(79) "http://distilleryimage6.s3.amazonaws.com/4c6f97c46a2c11e180c9123138016265_7.jpg" ["width"]=> int(612) ["height"]=> int(612) } } ["caption"]=> object(stdClass)#15 (4) { ["created_time"]=> string(10) "1331327500" ["text"]=> string(30) "Chillin with Brady at Stanford" ["from"]=> object(stdClass)#16 (4) { ["username"]=> string(14) "nicolelainefox" ["profile_picture"]=> string(54) "http://images.instagram.com/profiles/anonymousUser.jpg" ["id"]=> string(8) "17982472" ["full_name"]=> string(14) "nicolelainefox" } ["id"]=> string(18) "143507936292283648" } ["type"]=> string(5) "image" ["id"]=> string(27) "143507334669706518_17982472" ["user"]=> object(stdClass)#17 (6) { ["username"]=> string(14) "nicolelainefox" ["website"]=> string(0) "" ["bio"]=> string(0) "" ["profile_picture"]=> string(54) "http://images.instagram.com/profiles/anonymousUser.jpg" ["full_name"]=> string(14) "nicolelainefox" ["id"]=> string(8) "17982472" } } } }
However, when I use echo($instagram_data["data"]); everything crashes. How do I access the 'data' array in this associative array? Here's the whole code:
$instagram_handler = fopen("https://api.instagram.com/v1/locations/10138861/media/recent/?client_id=MY_ID", "r");
$instagram_json = stream_get_contents($instagram_handler);
fclose($instagram_handler);
$instagram_data = json_decode($instagram_json);
echo($instagram_data["data"]); //Breaks page
the JSON is read as an object, not an associative array. load it like so and you'll be good:
$instagram_data = json_decode($instagram_json, TRUE);
alternatively, loading it like you do currently, run:
echo $instagram_data->data
Note the assoc param of json_decode function. If you omit it decode treats JSON as an object rather than an array. So you should be able access it with:
$instagram_data->data;
Other option is to decode as array as following:
$instagram_data = json_decode($instagram_json, TRUE);