php multi dimension array? - php

I am retrieving a multidimensional php array (I think) from an API, now all of the values return perfectly and when I dump the array with print_r I get this:
Event Object
(
[title] => test
[link] => google.com
[updated] => 2013-03-06T12:08:56.521-05:00
[id] => test
[name] => Copy of Copy of Copy of Mar 05, 2013 - TEST4
[description] =>
[registered] => 2
[createdDate] => 2013-03-06T12:08:56.521-05:00
[status] => COMPLETE
[eventType] => OTHER
[eventLocation] => EventLocation Object
(
[location] => test
[addr1] => test
[addr2] =>
[addr3] =>
[city] => madrid
[state] => andalucia
[country] =>
[postalCode] => 06103
)
[registrationUrl] => https://google.com
[startDate] => 2013-03-07T13:00:00-05:00
[endDate] => 2013-03-07T13:00:00-05:00
[publishDate] => 2013-03-06T12:11:15.958-05:00
[attendedCount] => 0
[cancelledCount] => 0
[eventFeeRequired] => FALSE
[currencyType] => USD
[paymentOptions] => Array
(
)
[registrationTypes] => Array
(
[0] => RegistrationType Object
(
[name] =>
[registrationLimit] =>
[registrationClosedManually] =>
[guestLimit] =>
[ticketing] =>
[eventFees] => Array
(
)
)
)
)
Now bumbling through wit my basic PHP i have found that i can list all of the first array items from [title] to [eventType] like this:
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
while (list($key, $value) = each($Event)) {
echo "$key => $value \r\n<br/>";
}
?>
my question: All I need to do it retrieve [title] and [startDate] I don't need the rest now I could just hide the rest using Js and css but i am sure i am just being an idiot and there is an easier way to traverse this array so it only spits out the two values i need.
How do i do this?

You do not have to traverse the whole object. Just access the properties you want:
$title = $Event->title;
$startDate = $Event->startDate;
// or
echo $Event->title;
echo $Event->startDate;
It's actually an object - not an (associative) array!
What's the difference?
An object is an instance of a class. A class has methods and attributes (member variables).
Unlike C++ or some other OOP languages, you can define attributes dynamically without declaring them in the class declaration.
An array is simply a container for keys and their values.

It seems that it's not an array but an object so something like this:
echo $Event->title;
echo $Event->startDate;

Is it ...
<?php
// get details for the first event returned
$Event = $ConstantContact->getEventDetails($events['events'][0]);
reset($Event);
echo $Event->$title . "<br/>";
echo $Event->$startDate . "<br/>";
?>
? Or am I too simple?

Related

Get value from complicate array having object

CoinGate\Merchant\Order Object
(
[order:CoinGate\Merchant\Order:private] => Array
(
[id] => 97977
[status] => new
[do_not_convert] =>
[price_currency] => USD
[price_amount] => 1200.0
[lightning_network] =>
[receive_currency] => EUR
[receive_amount] =>
[created_at] => 2018-07-03T05:53:43+00:00
[order_id] => 459469
[payment_url] => https://sandbox.coingate.com/invoice/94423345-1a1a-4895-a08e-98793777b0d0
[token] => x5Yrx5mmku8nkyK2ShVvbCuiJfasoxsNBtxZ27Ra
)
)
This is response of request but i am facing to get values from such array. I need to get payment_url from such array.
In a Order.php file there's a magic __get method. So, you should use it to get the property you need:
// suppose $response is the value you `var_dump`ed in a question.
echo $response->payment_url; // same for other properties: $response->status
get_object_vars function in PHP convert object to array. Consider you are having this object in variable $x, then you should do like:
$y = get_object_vars($x);
echo $y['payment_url'];

php - Parse Goole Books PI JSON [duplicate]

This question already has answers here:
Using Google Books API
(2 answers)
Closed 5 years ago.
I have written a PHP code to parse the data pobidd by GoogleBooks API
<?php
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode($json, true);
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["title"];
echo $obj["volumeInfo"]["subtitle"];
echo $obj["volumeInfo"]["authors"];
echo $obj["volumeInfo"]["printType"];
echo $obj["volumeInfo"]["pageCount"];
echo $obj["volumeInfo"]["publisher"];
echo $obj["volumeInfo"]["publishedDate"];
echo $obj["accessInfo"]["webReaderLink"];
?>
When execute it, I get
Notice: Undefined index: volumeInfo in /storage/ssd3/164/2474164/public_html/dev/fetch/v2.php on line 8
for all the echo strings , so I re-checked all possible sources of problem without solution
You're accessing the array elements in the wrong way. Do var_dump($obj); or echo '<pre>'; print_r($obj); echo '</pre>'; to see the complete array structure. Your echo statements would be like this:
echo $obj['items'][0]["volumeInfo"]["title"] . '<br />';
// echo $obj['items'][0]["volumeInfo"]["subtitle"];
echo $obj['items'][0]["volumeInfo"]["authors"][0] . '<br />';
echo $obj['items'][0]["volumeInfo"]["printType"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["pageCount"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publisher"] . '<br />';
echo $obj['items'][0]["volumeInfo"]["publishedDate"] . '<br />';
echo $obj['items'][0]["accessInfo"]["webReaderLink"] . '<br />';
Not sure whether you would be getting subtitle information along with the book details. If so, then please uncomment that line.
To my mind it is far easier to use the object notation for accessing the various properties of the JSON response rather than the clunky array syntax but you need to identify the correct location in the object/array heirarchy before attempting to access the sub-keys of it.
$isbn = "9781451648546"; // Steve Jobs book
$json = file_get_contents('https://www.googleapis.com/books/v1/volumes?q=isbn:'.$isbn);
$obj = json_decode( $json );
$items=$obj->items;
foreach( $items as $item ){
/* Main keys */
$vol=$item->volumeInfo;
$sales=$item->saleInfo;
$access=$item->accessInfo;
$info=$item->searchInfo;
/* subkeys */
$title=$vol->title;
$authors=implode( $vol->authors );
$type=$vol->printType;
/* etc */
echo $title, $authors, $type, '<br />';//etc
}
/* to clearly see the data structure try this: */
echo '<pre>',print_r($obj,true),'</pre>';
Will output
Steve JobsWalter IsaacsonBOOK
stdClass Object
(
[kind] => books#volumes
[totalItems] => 1
[items] => Array
(
[0] => stdClass Object
(
[kind] => books#volume
[id] => 8U2oAAAAQBAJ
[etag] => Cfd5hfOLjks
[selfLink] => https://www.googleapis.com/books/v1/volumes/8U2oAAAAQBAJ
[volumeInfo] => stdClass Object
(
[title] => Steve Jobs
[authors] => Array
(
[0] => Walter Isaacson
)
[publisher] => Simon and Schuster
[publishedDate] => 2011
[description] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
[industryIdentifiers] => Array
(
[0] => stdClass Object
(
[type] => ISBN_13
[identifier] => 9781451648546
)
[1] => stdClass Object
(
[type] => ISBN_10
[identifier] => 1451648545
)
)
[readingModes] => stdClass Object
(
[text] =>
[image] =>
)
[pageCount] => 630
[printType] => BOOK
[categories] => Array
(
[0] => Biography & Autobiography
)
[averageRating] => 4
[ratingsCount] => 3904
[maturityRating] => NOT_MATURE
[allowAnonLogging] =>
[contentVersion] => 0.3.0.0.preview.0
[imageLinks] => stdClass Object
(
[smallThumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api
[thumbnail] => http://books.google.com/books/content?id=8U2oAAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api
)
[language] => en
[previewLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&printsec=frontcover&dq=isbn:9781451648546&hl=&cd=1&source=gbs_api
[infoLink] => http://books.google.co.uk/books?id=8U2oAAAAQBAJ&dq=isbn:9781451648546&hl=&source=gbs_api
[canonicalVolumeLink] => https://books.google.com/books/about/Steve_Jobs.html?hl=&id=8U2oAAAAQBAJ
)
[saleInfo] => stdClass Object
(
[country] => GB
[saleability] => NOT_FOR_SALE
[isEbook] =>
)
[accessInfo] => stdClass Object
(
[country] => GB
[viewability] => PARTIAL
[embeddable] => 1
[publicDomain] =>
[textToSpeechPermission] => ALLOWED_FOR_ACCESSIBILITY
[epub] => stdClass Object
(
[isAvailable] =>
)
[pdf] => stdClass Object
(
[isAvailable] =>
)
[webReaderLink] => http://play.google.com/books/reader?id=8U2oAAAAQBAJ&hl=&printsec=frontcover&source=gbs_api
[accessViewStatus] => SAMPLE
[quoteSharingAllowed] =>
)
[searchInfo] => stdClass Object
(
[textSnippet] => Draws on more than forty interviews with Steve Jobs, as well as interviews with family members, friends, competitors, and colleagues to offer a look at the co-founder and leading creative force behind the Apple computer company.
)
)
)
)

PHP - Converting XML to array misses some information from XML string

I am using curl to get an external XML document and convert it to an array.
The code works almost perfect, apart from one node in the XML isn't being processed and put in my array.
Under <drivers> there is a code for each driver: <driver code="TM1"> but this doesn't get picked up by my array as an #attribute array like the others such as <collection date="20160324">
Does anybody know why this is happening?
XML:
<findit xmlns="http://www.URL.COM" version="8" type="TIX" date="20160323">
<account code="XXXXXX">
<customers>
<customer code="12345">
<status code="0">Success</status>
<logistic-jobs>
<logistic-job id="12345" date="20160324" status="PLA" modified="201603231420">
<number>
<number1>479599</number1>
<number3>11221</number3>
</number>
<collection date="20160324" time="0500">
<name>JOHN SMITH</name>
<address1>UNIT 3 DAVEY ROAD</address1>
<address2>FIELDS END BUSINESS PARK</address2>
<address3>GOLDTHORPE</address3>
<address4>ROTHERHAM</address4>
<address5>S63 0JF</address5>
</collection>
<delivery date="20160324" time="1200">
<address1>EXAMPLE</address1>
<address2>GLENEAFLES FARM</address2>
<address3>GLENEAGLES CLOSE</address3>
<address4>STANWELL, MIDDLESEX</address4>
<address5>TW19 7PD</address5>
</delivery>
<extra>
<address1>45FT C/SIDER</address1>
<address2>No</address2>
<address4>CEMENT</address4>
</extra>
<drivers>
<driver code="TM1">DAVE SMITH (DAYS)</driver>
</drivers>
<load weight="27600.00" volume="0.00">
<pallets full="23" half="0" quarter="0" blue="0" oversize="0"/>
</load>
</logistic-job>
</logistic-jobs>
</customer>
</customers>
</account>
</findit>
PHP:
$job_array = json_decode(json_encode(simplexml_load_string($xml)), true);
if(is_array($job_array['account']['customers']['customer'])) {
// Foreach customer in array
foreach($job_array['account']['customers']['customer'] as $i => $customer) {
// If status is set to success
if($customer['status'] == "Success") {
// For each job
foreach($customer['logistic-jobs']['logistic-job'] as $i => $job) {
echo '<pre>'; print_r($job); echo '</pre>';
}
}
}
}
OUTPUT:
Array
(
[#attributes] => Array
(
[id] => 12345
[date] => 20160324
[status] => PLA
[modified] => 201603231420
)
[number] => Array
(
[number1] => 479599
[number3] => 11221
)
[collection] => Array
(
[#attributes] => Array
(
[date] => 20160324
[time] => 0500
)
[name] => JOHN SMITH
[address1] => UNIT 3 DAVEY ROAD
[address2] => FIELDS END BUSINESS PARK
[address3] => GOLDTHORPE
[address4] => ROTHERHAM
[address5] => S63 0JF
)
[delivery] => Array
(
[#attributes] => Array
(
[date] => 20160324
[time] => 1200
)
[address1] => EXAMPLE
[address2] => GLENEAFLES FARM
[address3] => GLENEAGLES CLOSE
[address4] => STANWELL, MIDDLESEX
[address5] = TW19 7PD
)
[extra] => Array
(
[address1] => 45FT C/SIDER
[address2] => No
[address4] => CEMENT
)
[drivers] => Array
(
[driver] => DAVE SMITH (DAYS)
)
[load] => Array
(
[#attributes] => Array
(
[weight] => 21509.00
[volume] => 0.00
)
[pallets] => Array
(
[#attributes] => Array
(
[full] => 52
[half] => 0
[quarter] => 0
[blue] => 0
[oversize] => 0
)
)
)
)
I have a simple answer for you: don't convert XML to an array. SimpleXML has a really useful API for traversing through the XML document and finding the data you want; throw away the horrible json_decode(json_encode( hack and look at the examples in the PHP manual.
In this case, echo $driver would give you the contents (driver name) and echo $driver['code'] would give you the attribute value; clearly, a plain array can't have that convenient magic, which is why converting to one is giving you problems.
Just remember that print_r will also hide things from you, and you might want a dedicated debugging function.
Here's an example (with live demo) of getting the code and name of each driver:
$job_simple = simplexml_load_string($xml);
if(isset($job_simple->account->customers->customer)) {
// Foreach customer in array
foreach($job_simple->account->customers->customer as $i => $customer) {
// If status is set to success
if((string)$customer->status == "Success") {
// For each job
foreach($customer->{'logistic-jobs'}->{'logistic-job'} as $i => $job) {
echo "<ul>\n";
foreach ( $job->drivers->driver as $driver ) {
echo "<li> {$driver['code']}: $driver\n";
}
echo "</ul>\n";
}
}
}
}

How to display info from an array in PHP?

If my array states:
[mostPlayedGames] => Array ( [0] => stdClass Object ( [gameName] => Counter-Strike: Global Offensive [gameLink] => http://steamcommunity.com/app/730 [gameIcon] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/69f7ebe2735c366c65c0b33dae00e12dc40edbe4.jpg [gameLogo] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/d0595ff02f5c79fd19b06f4d6165c3fda2372820.jpg [gameLogoSmall] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/730/d0595ff02f5c79fd19b06f4d6165c3fda2372820_thumb.jpg [hoursPlayed] => 28.0 [hoursOnRecord] => 527 [statsName] => CSGO ) [1] => stdClass Object ( [gameName] => Borderlands: The Pre-Sequel [gameLink] => http://steamcommunity.com/app/261640 [gameIcon] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/af5ef05eac8b1eb618e4f57354ac7b3e918ab1bd.jpg [gameLogo] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/df64c72fd335a03dbcc0a19b1f81acc8db1b94ba.jpg [gameLogoSmall] => http://cdn.akamai.steamstatic.com/steamcommunity/public/images/apps/261640/df64c72fd335a03dbcc0a19b1f81acc8db1b94ba_thumb.jpg [hoursPlayed] => 10.9 [hoursOnRecord] => 10.9 [statsName] => 261640 )
and I want to display info from the first part of the array( 0 ), how would I go about doing that if I was using code like this to display it:
echo "CS:GO Hours Played: {$user->mostPlayedGames???}, PHP_EOL;
Thank you for your time.
Your mostPlayedGames array doesn't seem like it is an stdClass of any variable named $user, so let's not over complicate it.
$mostPlayedGames = [mostPlayedGames] => Array ( [0] => stdClass Object ( [gameName]....[snippet]
Now that we have that clear:
echo "CS:GO Hours Played: ${mostPlayedGames[0]->hoursPlayed}".PHP_EOL;
You see, The first element in this is an array at position 0 so we must first move to that index position. The element at index 0 is an stdClass so then we can use the accessor method -> to grab properties of this object.

foreach loops & stdclass objects

I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );

Categories