Basically I have an array of objects that I've managed to dump. I'm trying to figure out how I can get the values from the [options] object from a set objects and store them in an array
array(4) {
["size"]=>
object(WC_Product_Attribute)#2724 (1) {
["data":protected]=>
array(6) {
["id"]=>
int(0)
["name"]=>
string(4) "Size"
["options"]=>
array(3) {
[0]=>
string(6) "400 ml"
[1]=>
string(2) "1L"
[2]=>
string(2) "2L"
}
["position"]=>
int(0)
["visible"]=>
bool(true)
["variation"]=>
bool(false)
}
}
["fruit"]=>
object(WC_Product_Attribute)#2723 (1) {
["data":protected]=>
array(6) {
["id"]=>
int(0)
["name"]=>
string(5) "Fruit"
["options"]=>
array(8) {
[0]=>
string(17) "100% Orange Juice"
[1]=>
string(5) "Apple"
[2]=>
string(4) "Pear"
[3]=>
string(9) "Pineapple"
[4]=>
string(12) "Passionfruit"
[5]=>
string(15) "Red Dragonfruit"
[6]=>
string(13) "Baobab Powder"
[7]=>
string(17) "Grapeseed Extract"
}
["position"]=>
int(1)
["visible"]=>
bool(true)
["variation"]=>
bool(false)
}
}
["good-source-of-vit-c"]=>
object(WC_Product_Attribute)#2722 (1) {
["data":protected]=>
array(6) {
["id"]=>
int(0)
["name"]=>
string(20) "Good Source of Vit C"
["options"]=>
array(1) {
[0]=>
string(3) "Yes"
}
["position"]=>
int(2)
["visible"]=>
bool(true)
["variation"]=>
bool(false)
}
}
["fiber"]=>
object(WC_Product_Attribute)#2721 (1) {
["data":protected]=>
array(6) {
["id"]=>
int(0)
["name"]=>
string(5) "Fiber"
["options"]=>
array(1) {
[0]=>
string(3) "Yes"
}
["position"]=>
int(3)
["visible"]=>
bool(true)
["variation"]=>
bool(false)
}
}
}
I've tried doing a foreach to loop through each object but I've stumbled upon an error.
foreach ($productsArray as $i => $value) {
echo $value->options;
}
My objective is to get all the values from the [options] object store them in an array to be used.
From what I can see you are iterating over an array of WC_Product_Attribute objects and that's a sign of WooCommerce usage, isn't it?
In that case there is a getter method available to get options from a Product Attribute:
foreach ($productsArray as $i => $value) {
var_dump( $value->get_options() );
}
More in the docs
I do get the strings I intend to. But I also get the first letter (or number) of the other data in the json file.
E.g. I would like to have or should get the result:
/Barrafina
Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.
Matt Ta-Min/
But instead I get
/Barrafina
ee
Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.
5 5 E Eu uh h
Matt Ta-Min
/
What did I do wrong? here is the code:
(If you have time and energy to look the JSON you will see from where eg. 5 5 E Eu uh h comes.)
I appreciate any help.
<?php
$client_id = 'CLIENT_ID';
$client_secret = 'SECRET';
$request_date = date('Ymd');
$base_url = 'https://api.foursquare.com/v2/';
$endpoint = 'venues/explore?';
$params = 'near=London&limit=3§ion=food&radius=1000';
$auth = "&client_id=$client_id&client_secret=$client_secret&v=$request_date";
$url = $base_url.$endpoint.$params.$auth;
$results = file_get_contents($url);
$json_results = json_decode($results,true);
//var_dump($json_results);
$items0 = $json_results['response']['groups']['0']['items']['0'];
$items1 = $json_results['response']['groups']['0']['items']['0']['tips'];
$items2 = $json_results['response']['groups']['0']['items']['0']['tips']['0'];
//<div style="align:center;">
foreach ( $items0+$items1 as $item){
echo '<li>';
echo $item['name'];
echo $item['text'];
}
foreach ( $items2 as $item){
print $item['firstName']; print ' '; print $item['lastName'];
}
HERE is the json decoded:
array(2) { ["meta"]=> array(2) { ["code"]=> int(200) ["requestId"]=> string(24) "55fb1f91498e70ad2e246eed" } ["response"]=> array(10) { ["suggestedFilters"]=> array(2) { ["header"]=> string(12) "Tap to show:" ["filters"]=> array(2) { [0]=> array(2) { ["name"]=> string(13) "With specials" ["key"]=> string(8) "specials" } [1]=> array(2) { ["name"]=> string(8) "Open now" ["key"]=> string(7) "openNow" } } } ["geocode"]=> array(8) { ["what"]=> string(0) "" ["where"]=> string(6) "london" ["center"]=> array(2) { ["lat"]=> float(51.50853) ["lng"]=> float(-0.12574) } ["displayString"]=> string(38) "London, Greater London, United Kingdom" ["cc"]=> string(2) "GB" ["geometry"]=> array(1) { ["bounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.691643999656) ["lng"]=> float(0.33418999705203) } ["sw"]=> array(2) { ["lat"]=> float(51.284674044171) ["lng"]=> float(-0.50855792793694) } } } ["slug"]=> string(6) "london" ["longId"]=> string(17) "72057594040571679" } ["warning"]=> array(1) { ["text"]=> string(114) "There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area." } ["headerLocation"]=> string(6) "London" ["headerFullLocation"]=> string(6) "London" ["headerLocationGranularity"]=> string(4) "city" ["query"]=> string(4) "food" ["totalResults"]=> int(246) ["suggestedBounds"]=> array(2) { ["ne"]=> array(2) { ["lat"]=> float(51.510800358799) ["lng"]=> float(-0.12174369837641) } ["sw"]=> array(2) { ["lat"]=> float(51.508100699014) ["lng"]=> float(-0.13015278468604) } } ["groups"]=> array(1) { [0]=> array(3) { ["type"]=> string(18) "Recommended Places" ["name"]=> string(11) "recommended" ["items"]=> array(1) { [0]=> array(4) { ["reasons"]=> array(2) { ["count"]=> int(0) ["items"]=> array(1) { [0]=> array(3) { ["summary"]=> string(20) "This spot is popular" ["type"]=> string(7) "general" ["reasonName"]=> string(23) "globalInteractionReason" } } } ["venue"]=> array(17) { ["id"]=> string(24) "53bab96d498e7e355fb53d6c" ["name"]=> string(9) "Barrafina" ["contact"]=> array(6) { ["phone"]=> string(13) "+442074401456" ["formattedPhone"]=> string(16) "+44 20 7440 1456" ["twitter"]=> string(13) "barrafinaadst" ["facebook"]=> string(15) "705351912878392" ["facebookUsername"]=> string(23) "BarrafinaAdelaideStreet" ["facebookName"]=> string(25) "Barrafina Adelaide Street" } ["location"]=> array(10) { ["address"]=> string(14) "10 Adelaide St" ["crossStreet"]=> string(13) "William IV St" ["lat"]=> float(51.509450528906) ["lng"]=> float(-0.12594824153122) ["postalCode"]=> string(8) "WC2N 4HZ" ["cc"]=> string(2) "GB" ["city"]=> string(6) "London" ["state"]=> string(14) "Greater London" ["country"]=> string(14) "United Kingdom" ["formattedAddress"]=> array(5) { [0]=> string(30) "10 Adelaide St (William IV St)" [1]=> string(6) "London" [2]=> string(14) "Greater London" [3]=> string(8) "WC2N 4HZ" [4]=> string(14) "United Kingdom" } } ["categories"]=> array(1) { [0]=> array(6) { ["id"]=> string(24) "4bf58dd8d48988d150941735" ["name"]=> string(18) "Spanish Restaurant" ["pluralName"]=> string(19) "Spanish Restaurants" ["shortName"]=> string(7) "Spanish" ["icon"]=> array(2) { ["prefix"]=> string(52) "https://ss3.4sqi.net/img/categories_v2/food/spanish_" ["suffix"]=> string(4) ".png" } ["primary"]=> bool(true) } } ["verified"]=> bool(false) ["stats"]=> array(3) { ["checkinsCount"]=> int(357) ["usersCount"]=> int(278) ["tipCount"]=> int(26) } ["url"]=> string(22) "http://barrafina.co.uk" ["price"]=> array(3) { ["tier"]=> int(2) ["message"]=> string(8) "Moderate" ["currency"]=> string(2) "£" } ["rating"]=> float(9) ["ratingColor"]=> string(6) "00B551" ["ratingSignals"]=> int(80) ["allowMenuUrlEdit"]=> bool(true) ["hours"]=> array(2) { ["status"]=> string(19) "Open until 11:00 PM" ["isOpen"]=> bool(true) } ["specials"]=> array(2) { ["count"]=> int(0) ["items"]=> array(0) { } } ["photos"]=> array(2) { ["count"]=> int(31) ["groups"]=> array(0) { } } ["hereNow"]=> array(3) { ["count"]=> int(0) ["summary"]=> string(11) "Nobody here" ["groups"]=> array(0) { } } } ["tips"]=> array(1) { [0]=> array(9) { ["id"]=> string(24) "55db9142498ede18f5b31b81" ["createdAt"]=> int(1440452930) ["text"]=> string(164) "Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here." ["type"]=> string(4) "user" ["canonicalUrl"]=> string(52) "https://foursquare.com/item/55db9142498ede18f5b31b81" ["likes"]=> array(3) { ["count"]=> int(2) ["groups"]=> array(0) { } ["summary"]=> string(7) "2 likes" } ["logView"]=> bool(true) ["todo"]=> array(1) { ["count"]=> int(0) } ["user"]=> array(5) { ["id"]=> string(8) "98683884" ["firstName"]=> string(4) "Matt" ["lastName"]=> string(6) "Ta-Min" ["gender"]=> string(4) "male" ["photo"]=> array(2) { ["prefix"]=> string(31) "https://irs1.4sqi.net/img/user/" ["suffix"]=> string(30) "/98683884-1MJ0OTISTPZWSBRJ.jpg" } } } } ["referralId"]=> string(30) "e-3-53bab96d498e7e355fb53d6c-0" } } } } } }
Here is JSON
{"meta":{"code":200,"requestId":"55fbde58498e7fdbd12f8fb2"},"response":{"suggestedFilters":{"header":"Tap to show:","filters":[{"name":"With specials","key":"specials"},{"name":"Open now","key":"openNow"}]},"geocode":{"what":"","where":"london","center":{"lat":51.50853,"lng":-0.12574},"displayString":"London, Greater London, United Kingdom","cc":"GB","geometry":{"bounds":{"ne":{"lat":51.691643999655895,"lng":0.33418999705203406},"sw":{"lat":51.28467404417054,"lng":-0.5085579279369435}}},"slug":"london","longId":"72057594040571679"},"warning":{"text":"There aren't a lot of results near you. Try something more general, reset your filters, or expand the search area."},"headerLocation":"London","headerFullLocation":"London","headerLocationGranularity":"city","query":"food","totalResults":246,"suggestedBounds":{"ne":{"lat":51.5108003587992,"lng":-0.12174369837640672},"sw":{"lat":51.50810069901375,"lng":-0.1301527846860385}},"groups":[{"type":"Recommended Places","name":"recommended","items":[{"reasons":{"count":0,"items":[{"summary":"This spot is popular","type":"general","reasonName":"globalInteractionReason"}]},"venue":{"id":"53bab96d498e7e355fb53d6c","name":"Barrafina","contact":{"phone":"+442074401456","formattedPhone":"+44 20 7440 1456","twitter":"barrafinaadst","facebook":"705351912878392","facebookUsername":"BarrafinaAdelaideStreet","facebookName":"Barrafina Adelaide Street"},"location":{"address":"10 Adelaide St","crossStreet":"William IV St","lat":51.50945052890648,"lng":-0.1259482415312226,"postalCode":"WC2N 4HZ","cc":"GB","city":"London","state":"Greater London","country":"United Kingdom","formattedAddress":["10 Adelaide St (William IV St)","London","Greater London","WC2N 4HZ","United Kingdom"]},"categories":[{"id":"4bf58dd8d48988d150941735","name":"Spanish Restaurant","pluralName":"Spanish Restaurants","shortName":"Spanish","icon":{"prefix":"https:\/\/ss3.4sqi.net\/img\/categories_v2\/food\/spanish_","suffix":".png"},"primary":true}],"verified":false,"stats":{"checkinsCount":357,"usersCount":278,"tipCount":26},"url":"http:\/\/barrafina.co.uk","rating":9.0,"ratingColor":"00B551","ratingSignals":80,"allowMenuUrlEdit":true,"hours":{"status":"Closed until Noon","isOpen":false},"specials":{"count":0,"items":[]},"photos":{"count":31,"groups":[]},"hereNow":{"count":0,"summary":"Nobody here","groups":[]}},"tips":[{"id":"55db9142498ede18f5b31b81","createdAt":1440452930,"text":"Exceptional cooking here. Such simple but amazing dishes. Highly recommend the crab croquettes, lambs kidneys, skewers and the brain. Sherries are also superb here.","type":"user","canonicalUrl":"https:\/\/foursquare.com\/item\/55db9142498ede18f5b31b81","likes":{"count":2,"groups":[],"summary":"2 likes"},"logView":true,"todo":{"count":0},"user":{"id":"98683884","firstName":"Matt","lastName":"Ta-Min","gender":"male","photo":{"prefix":"https:\/\/irs1.4sqi.net\/img\/user\/","suffix":"\/98683884-1MJ0OTISTPZWSBRJ.jpg"}}}],"referralId":"e-3-53bab96d498e7e355fb53d6c-0"}]}]}}
New PHP user left scratching my head. This function contains two foreach loops nested in if/else the page is index.php. On index.php, the code works fine, and the page shows the last four items in the array.
However, if the page is NOT index.php, the array seems to have been affected by code in between the first and second foreach loop, and only shows as a 1D array with the first-level keys as integers. How do I fix this? I've gone through virtually every PHP documentation I can find with no success.
function list_products_html($products) {
//If page is INDEX.PHP, show only last 4 products in reverse order with PayPal drop-down and Add To Cart
if ($_SERVER['PHP_SELF'] == "index.php") {
$products_reverse = array_reverse($products, true);
$products_new = array_slice($products_reverse, 0, 4, true);
foreach ($products_new as $product_new_id => $product_new) {
echo list_product_html($products_new);
echo generate_paypal_form($products_new);
echo '</li>';
}
//Else, show all products
} else {
foreach ($products as $product_id => $product) {
echo list_product_html($products);
echo generate_paypal_form($products);
echo '</li>';
}
}
}
In the first foreach loop, the var_dump shows my array as the following (which is correct):
array(8) { [101]=> array(5) { ["name"]=> string(15) "Logo Shirt, Red" ["img"]=> string(24) "img/shirts/shirt-101.jpg" ["price"]=> int(18) ["paypal"]=> string(13) "BJDE2BMPHMQ7Q" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [102]=> array(5) { ["name"]=> string(26) "Mike the Frog Shirt, Black" ["img"]=> string(24) "img/shirts/shirt-102.jpg" ["price"]=> int(20) ["paypal"]=> string(13) "2H6VLSYHY3QC8" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [103]=> array(5) { ["name"]=> string(25) "Mike the Frog Shirt, Blue" ["img"]=> string(24) "img/shirts/shirt-103.jpg" ["price"]=> int(20) ["paypal"]=> string(13) "MDP23L74U3F4L" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [104]=> array(5) { ["name"]=> string(17) "Logo Shirt, Green" ["img"]=> string(24) "img/shirts/shirt-104.jpg" ["price"]=> int(18) ["paypal"]=> string(13) "Q39L2XSPANB3Y" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [105]=> array(5) { ["name"]=> string(27) "Mike the Frog Shirt, Yellow" ["img"]=> string(24) "img/shirts/shirt-105.jpg" ["price"]=> int(25) ["paypal"]=> string(13) "7LVQ78CEPSKVN" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [106]=> array(5) { ["name"]=> string(16) "Logo Shirt, Gray" ["img"]=> string(24) "img/shirts/shirt-106.jpg" ["price"]=> int(20) ["paypal"]=> string(13) "G9A9UEVWCTDQN" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [107]=> array(5) { ["name"]=> string(21) "Logo Shirt, Turquoise" ["img"]=> string(24) "img/shirts/shirt-107.jpg" ["price"]=> int(20) ["paypal"]=> string(13) "NNERMRTJSTG6Q" ["sizes"]=> array(4) { [0]=> string(5) "Small" [1]=> string(6) "Medium" [2]=> string(5) "Large" [3]=> string(7) "X-Large" } } [108]=> array(5) { ["name"]=> string(18) "Logo Shirt, Orange" ["img"]=> string(24) "img/shirts/shirt-108.jpg" ["price"]=> int(25) ["paypal"]=> string(13)
In the SECOND foreach loop, I am getting the
"Warning: Invalid argument supplied for foreach()"
error, because var_dump for the same $products array shows the following:
int(101) int(102) int(103) int(104) int(105) int(106) int(107)
int(108)
I have the array like this:
} ["items":"Jcart":private]=> array(3) {
[0]=>
string(1) "3"
[1]=>
string(1) "2"
[2]=>
string(7) "ABC-123" }
How to get the "items" values in a php variable?
///////
Te complete object is:
object(Jcart)#1 (8) {
["config"]=>
array(12) {
["jcartPath"]=>
string(6) "jcart/"
["checkoutPath"]=>
string(12) "checkout.php"
["item"]=>
array(6) {
["id"]=>
string(10) "my-item-id"
["name"]=>
string(12) "my-item-name"
["price"]=>
string(13) "my-item-price"
["qty"]=>
string(11) "my-item-qty"
["url"]=>
string(11) "my-item-url"
["add"]=>
string(13) "my-add-button"
}
["paypal"]=>
array(5) {
["id"]=>
string(38) "seller_1282188508_biz#conceptlogic.com"
["https"]=>
bool(true)
["sandbox"]=>
bool(false)
["returnUrl"]=>
string(0) ""
["notifyUrl"]=>
string(0) ""
}
["currencyCode"]=>
string(3) "USD"
["csrfToken"]=>
bool(false)
["text"]=>
array(14) {
["cartTitle"]=>
string(13) "Shopping Cart"
["singleItem"]=>
string(4) "Item"
["multipleItems"]=>
string(5) "Items"
["subtotal"]=>
string(8) "Subtotal"
["update"]=>
string(6) "update"
["checkout"]=>
string(8) "checkout"
["checkoutPaypal"]=>
string(20) "Checkout with PayPal"
["removeLink"]=>
string(6) "remove"
["emptyButton"]=>
string(5) "empty"
["emptyMessage"]=>
string(19) "Your cart is empty!"
["itemAdded"]=>
string(11) "Item added!"
["priceError"]=>
string(21) "Invalid price format!"
["quantityError"]=>
string(38) "Item quantities must be whole numbers!"
["checkoutError"]=>
string(34) "Your order could not be processed!"
}
["button"]=>
array(4) {
["checkout"]=>
string(0) ""
["paypal"]=>
string(0) ""
["update"]=>
string(0) ""
["empty"]=>
string(0) ""
}
["tooltip"]=>
bool(true)
["decimalQtys"]=>
bool(false)
["decimalPlaces"]=>
int(1)
["priceFormat"]=>
array(3) {
["decimals"]=>
int(2)
["dec_point"]=>
string(1) "."
["thousands_sep"]=>
string(1) ","
}
}
["items":"Jcart":private]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "2"
}
["names":"Jcart":private]=>
array(2) {
[3]=>
string(12) "Hockey Stick"
[2]=>
string(13) "Baseball Mitt"
}
["prices":"Jcart":private]=>
array(2) {
[3]=>
string(5) "33.25"
[2]=>
string(5) "19.50"
}
["qtys":"Jcart":private]=>
array(2) {
[3]=>
string(1) "1"
[2]=>
string(2) "20"
}
["urls":"Jcart":private]=>
array(2) {
[3]=>
string(15) "http://bing.com"
[2]=>
string(16) "http://yahoo.com"
}
["subtotal":"Jcart":private]=>
float(423.25)
["itemCount":"Jcart":private]=>
int(21)
}
I just need the values in ["items":"Jcart":private]
I assume you got this by casting an object to an array. If that's the case, you shouldn't be doing that! The property is private because you're not supposed to access it directly because it's not a public API. The object should have a public method which you're supposed to call instead, that's the public API. Something like $foo->getItems() or such. Read the documentation and/or source code.
I am having trouble targeting the particular value in the array. I am trying to target the 'lng' and 'lat'. I feel like I'm close, and have tried several different ways to target. Currently trying this:
$json = file_get_contents($jsonurl);
$output = json_decode($json, true);
$latitude=$output['results']['locations']['latLng'][0];
$longitude=$output['results']['locations']['latLng'][1];
The JSON is:
array(3) {
["results"]=>
array(1) {
[0]=>
array(2) {
["locations"]=>
array(1) {
[0]=>
array(19) {
["latLng"]=>
array(2) {
["lng"]=>
float(-122.5008)
["lat"]=>
float(47.2629)
}
["adminArea4"]=>
string(13) "Pierce County"
["adminArea5Type"]=>
string(4) "City"
["adminArea4Type"]=>
string(6) "County"
["adminArea5"]=>
string(6) "Tacoma"
["street"]=>
string(0) ""
["adminArea1"]=>
string(2) "US"
["adminArea3"]=>
string(2) "WA"
["type"]=>
string(1) "s"
["displayLatLng"]=>
array(2) {
["lng"]=>
float(-122.5008)
["lat"]=>
float(47.2629)
}
["linkId"]=>
int(0)
["postalCode"]=>
string(5) "98406"
["sideOfStreet"]=>
string(1) "N"
["dragPoint"]=>
bool(false)
["adminArea1Type"]=>
string(7) "Country"
["geocodeQuality"]=>
string(3) "ZIP"
["geocodeQualityCode"]=>
string(5) "Z1XAA"
["mapUrl"]=>
string(186) "http://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luub2gu2ll,7w=o5-9uaauz&type=map&size=225,160&pois=purple-1,47.2629,-122.5008,0,0|¢er=47.2629,-122.5008&zoom=12&rand=-8386350"
["adminArea3Type"]=>
string(5) "State"
}
}
["providedLocation"]=>
array(1) {
["location"]=>
string(5) "98406"
}
}
}
["options"]=>
array(3) {
["ignoreLatLngInput"]=>
bool(false)
["maxResults"]=>
int(-1)
["thumbMaps"]=>
bool(true)
}
["info"]=>
array(3) {
["copyright"]=>
array(3) {
["text"]=>
string(22) "© 2013 MapQuest, Inc."
["imageUrl"]=>
string(35) "http://api.mqcdn.com/res/mqlogo.gif"
["imageAltText"]=>
string(22) "© 2013 MapQuest, Inc."
}
["statuscode"]=>
int(0)
["messages"]=>
array(0) {
}
}
}
Try
$latitude=$output['results'][0]['locations'][0]['latLng']['lat'];
$longitude=$output['results'][0]['locations'][0]['latLng']['lng'];