Echo out from a multidimensional array - php

I have this array:
Array
(
[result] => Array
(
[lastModified] => 1465097340000
[name] => Ulminia
[realm] => Zangarmarsh
[battlegroup] => Rampage
[class] => 3
[race] => 4
[gender] => 1
[level] => 100
[achievementPoints] => 14915
[thumbnail] => hellscream/74/113337162-avatar.jpg
[calcClass] => Y
[faction] => 0
[items] => Array
(
[averageItemLevel] => 710
[averageItemLevelEquipped] => 709
[head] => Array
(
[id] => 125899
[name] => Warmongering Gladiator's Helm
[icon] => inv_helm_mail_raidhunter_p_01
[quality] => 4
[itemLevel] => 710
[tooltipParams] => Array
(
[transmogItem] => 71356
[timewalkerLevel] => 100
)
I want to echo out from the [head] array the [id] and the [quality]. If i just echo out the [id] everything works, but if i want to echo out the [quality] too, it doesn´t work.
My code:
$items = $r['result']['items'];
echo 'Head: '.$items['head']['id']['quality']."\n";
foreach($items['head']['tooltipParams'] as $key => $value){
echo 'head_'.$key.': '.$value.'\n';
}

echo $items['head']['id']['quality'];
The above statement means you are printing out the subkey "quality" of key "id", which doesn't exist.
You need to concatenate both key values as follows:
echo $items['head']['id'] . ' ' . $items['head']['quality'];
... or
echo $items['head']['id'], ' ', $items['head']['quality'];

$items['head']['id']['quality']."\n"; is trying to read the element with the key quality inside the array stored inside id. However, id is not an array, which is why this fails.
In order to read two fields, you need to read them seperately:
echo 'Head: ID=' . $items['head']['id'] . ', quality = ' . $items['head']['quality'] . "\n";

Notice that the id and the quality are in the same array.
//ID
echo $items['head']['id'];
//Quality
echo $items['head']['quality'];

Related

Get values from Multi-dim Array

I do not understand why I can't echo out specific values out of my array..
I grab the $_POST output and save it to an array, filter the array to remove empty keys, display the array, that works all OK, then I try to specify a specific value and I get nothing.
echo "Post OrderArray<pre>";
print_r($_POST[order]);
echo "</pre>";
$order_list = $_POST[order];
$order_list = array_filter(array_map('array_filter', $order_list));
echo "order_list<pre>";
print_r($order_list);
echo "</pre>";
// try to output specific values
echo $order_list[0]['code'] . " _ " . $order_list[0]['qty'] . "<br />";
Post Order Array
Array
(
[0] => Array
(
['qty'] => 3
['code'] => 29468
)
[1] => Array
(
['qty'] =>
)
[2] => Array
(
['qty'] =>
)
[3] => Array
(
['qty'] =>
)
[4] => Array
(
['qty'] =>
)
)
Filtered Order_list Array
Array
(
[0] => Array
(
['qty'] => 3
['code'] => 29468
)
)
_
I think I should be getting "29468 _ 3" but I am not getting any values out of the array.
I copied your sample and added quotes when you are accessing $_POST and am getting the expected output.
If you do not use quotes you will get a notice similar the following depending on your PHP version:
Notice: Use of undefined constant order - assumed 'order' in /private/tmp/post.php on line 13
If you are using PHP 7.1.8 or less the script should still execute without issue. If you are using PHP 7.2 then this behaviour has been deprecated and will not run. You can find more info about this in this related answer.
Working script (in PHP 7.1.8):
// Manually set this for testing...
$_POST = [
'order' => [
['qty' => 3, 'code' => 29468],
['qty' => null],
['qty' => null],
['qty' => null],
['qty' => null],
]
];
echo "Post OrderArray<pre>";
print_r($_POST['order']); // Added quotes
echo "</pre>";
$order_list = $_POST['order']; // Added quotes
$order_list = array_filter(array_map('array_filter', $order_list));
echo "order_list<pre>";
print_r($order_list);
echo "</pre>";
// try to output specific values
echo $order_list[0]['code'] . " _ " . $order_list[0]['qty'] . "<br />";
Output:
php post.php
Post OrderArray<pre>Array
(
[0] => Array
(
[qty] => 3
[code] => 29468
)
[1] => Array
(
[qty] =>
)
[2] => Array
(
[qty] =>
)
[3] => Array
(
[qty] =>
)
[4] => Array
(
[qty] =>
)
)
</pre>order_list<pre>Array
(
[0] => Array
(
[qty] => 3
[code] => 29468
)
)
</pre>29468 _ 3<br />
I found my error, when I was creating the array I used:
$checkboxdata = "<input type=\"checkbox\" name=\"order[$x]['code']\" value=\"$sku\" />$sku";
$qty_checkbox = "<input type=\"text\" name=\"order[$x]['qty']\" class=\"spinner-1\" value=\"\" />";
so my array looked like:
Array
(
[0] => Array
(
['qty'] => 1
['code'] => 29468
Notice the quote marks.
When I edited my code to :
$checkboxdata = "<input type=\"checkbox\" name=\"order[$x][code]\" value=\"$sku\" />$sku";
$qty_checkbox = "<input type=\"text\" name=\"order[$x][qty]\" class=\"spinner-1\" value=\"\" />";
By removing the quotes, I can now access and get my individual values.
I knew it was something silly, and I was right.
Thanks to all for their assistance.
G

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.
)
)
)
)

Nested Associative Arrays printed as a Table

Good afternoon. I am fairly new to php and so apologise in advance if my question is a little simplistic for this forum.
I have a PHP associative array with some nested sub arrays that I wish to echo as a table. Here is the array:
Array
(
[message] => Your request was executed successfully.
[errors] => [warnings] => Array ( )
[request_timestamp] => 04-08-2016 21:43:06
[response_timestamp] => 04-08-2016 21:43:06
[request_id] => abcd1234
[branch] => Array
(
[location_id] => 157499
)
[property] => Array
(
[0] => Array
(
[agent_ref] => WR37EF-453625
[update_date] =>
[client_id] => 60462053
[channel] => 2
)
[1] => Array
(
[agent_ref] => Prop950
[update_date] => 04-08-2016
[client_id] => 60457613
[channel] => 2
)
[prop2] => Array
(
[agent_ref] => WR40rp-632482
[update_date] => 04-08-2016
[client id] => 60461789
[channel] => 2
)
[prop3] => Array
(
[agent_ref] => WR38UU-243564
[update_date] => 04-08-2016
[id] => 60461807
[channel] => 2
)
[prop4] => Array
(
[agent_ref] => WR3HMWR3HM-145622
[update_date] => 04-08-2016
[client id] => 60462014
[channel] => 2
)
)
)
What I am trying [and miserably failing to achieve] is a table (preceded with a non-table Titles Area) in the following format....
Title Area:-
message: Your request was executed successfully.
errors: a, b, c,
request timestamp: 04-08-2016 21:43:06
response timestamp: 04-08-2016 21:43:06
request id: abcd1234
customer id: 157499
followed by ...
Table Design where:-
..Rows are sub array names : [0] ; [1] ; [2]; [3]
..Column Header Names are the sub array $keys: agent_ref; update_date; client id; channel
..the row-col values are the sub array $values.
I am aware I probably need to use the foreach loop method. But getting the key-value pair out of the nested arrays in the titles/table format I need I am really struggling with.
Any help or guidance would be hugely appreciated.
Thank you
Something like this:
<?php
extract($your_array);
echo "$message<br>";
echo "$request_id<br>"; ...etc.
..
$first=true;
echo "<table>";
foreach($property as $propkey=>$propdets) {
if ($first) { // on first row - do headings
$heads=array_keys($propdets); // gets the keys for headings
echo "<tr><th>Item</th>";
foreach($heads as $hdng) {
echo "<th>$hdng</th>";
}
echo "</tr>";
}
$first=false;
echo "<tr><td>$propkey</td>"; // first column is the key(Item) - 0,1,prop2,prop3 etc.
foreach ($propdets as $pdet) { // then loop through the details
echo "<td>$pdet</td>";
}
echo "</tr>";
}
echo "</table>";
...
...
?>

Multidimensionnal ARRAY - 3 and 4 levels

I have this 3 and 4 multidimensionnal array ($response) which I need to "extract" some values.
Array (
[status] => 200
[response] => Array (
[api_id] => 38229dd9-8c52-11e5-80f6-22000afd0039
[meta] => Array (
[limit] => 20
[next] => /v1/Account/xxx/Call/?limit=20&offset=20
[offset] => 0
[previous] =>
[total_count] => 57 )
[objects] => Array (
[0] => Array (
[answer_time] => 2015-11-13 18:36:19+01:00
[bill_duration] => 10
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 10
[call_uuid] => dcd94e59-8775-4c81-a4b1-cd5d41d630c6
[end_time] => 2015-11-13 18:36:29+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 18:36:18+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/dcd94e59-8775-4c81-a4b1-cd5d41d630c6/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
[1] => Array (
[answer_time] => 2015-11-13 15:52:01+01:00 [
bill_duration] => 48
[billed_duration] => 60
[call_direction] => inbound
[call_duration] => 48
[call_uuid] => b2d3de5d-a047-4409-9f7a-825373c38f0a
[end_time] => 2015-11-13 15:52:48+01:00
[from_number] => 3300000000
[initiation_time] => 2015-11-13 15:52:00+01:00
[parent_call_uuid] =>
[resource_uri] => /v1/Account/xxx/Call/b2d3de5d-a047-4409-9f7a-825373c38f0a/
[to_number] => 3300000000
[total_amount] => 0.00500
[total_rate] => 0.00500 )
...
In the [meta] array, I need the [total_count] value and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
I have tried foreach within foreach or access datas with $response[0][0][0] but nothing do.
If someone could lead me to the solution...
Thanks a lot !!
You can access the meta array through $response['response']['meta']. As you can see from your array, both response and meta are keys, and so is total_count. Hence, accessing total count is done by $response['response']['meta']['total_count'].
To then loop through all your objects, simply do
foreach ($response['response']['objects'] as $object) {
print_r($object);
}
You can also access every attribute of the object individually by using the array keys:
foreach ($response['response']['objects'] as $object) {
echo $object['answer_time'];
echo $object['bill_duration'];
echo $object['billed_duration'];
echo $object['call_direction'];
echo $object['call_duration'];
echo $object['call_uuid'];
echo $object['end_time'];
echo $object['from_number'];
echo $object['initiation_time'];
echo $object['parent_call_uuid'];
echo $object['resource_uri'];
echo $object['to_number'];
echo $object['total_amount'];
echo $object['total_rate'];
}
First, to verify, if $array is the name of your array:
$response = $array["response"];
In the [meta] array, I need the [total_count] value
echo $response["meta"]["total_count"];
and for the [object] array, I'd like to get all the values to disaply them in a row (each object is a new row).
Use a foreach() function for all the objects:
foreach($response["objects"] as $object){
print_r($object);
}
You can use the "count" function with "COUNT_RECURSIVE" flag. It counts all the items inside the 'mixed' var. It counts parent element too.
count($array['objects'],COUNT_RECURSIVE);
example
$cibo = array(
'frutta' => array('arancia', 'banana', 'mela'),
'verdura' => array('carota', 'zucchina', 'piselli')
);
echo count($cibo,COUNT_RECURSIVE); // output 8

Ordering Array by value

I'm pulling in a list of my vimeo albums using the Vimeo API and the looping three times through the array to get to the albums. It works fine.
My question is, I'm isolating the date, so how can I create a new array and sort it by the date?
While where at it, is there a way to jump to the third level of a multi-dimensional array?
$albums=$vimeo->call('vimeo.albums.getAll', array('user_id' => $myUserId));
$albums_array=object_2_array($albums);
foreach($albums_array as $album_array_two){
foreach($album_array_two as $album_array_three){
foreach($album_array_threeas $album){
if(stristr($album['title'],'conference')){
$title=$album['title'];
$description=$album['description'];
$date=stristr($album['description'],'.',true);
$year_comma=stristr($date,',');
$year=ereg_replace("[^0-9]", "", $year_comma);
$url_title='http://www.psfk.com/events/'.str_replace( " ", "-", strtolower($title));
$url=''.$title.'';
$thumb=$album['thumbnail_video']['thumbnails']['thumbnail'][1]['_content'];
echo '<li class="album">';
echo '<img src="'.$thumb.'" alt="'.$title.'" />';
echo '<div class="info">';
echo '<h2>'.$url.'</h2>';
echo $description.'<br />';
echo 'View...';
echo '</div></li>';
}
}
}
}
Sample of the array returning one item:
Array (
[generated_in] => 0.0828
[stat] => ok
[albums] => Array (
[on_this_page] => 7
[page] => 1
[perpage] => 50
[total] => 7
[album] => Array (
[0] => Array (
[id] => 1690236
[title] => Interviews
[description] =>
[created_on] => 2011-09-10 21:43:49
[total_videos] => 1
[url] => Array (
[0] => http://vimeo.com/album/1690236
)
[video_sort_method] =>
[thumbnail_video] => Array (
[id] => 28825158
[owner] => 718882
[title] => Where Inspiration Comes From [thumbnails] => Array (
[thumbnail] => Array (
[0] => Array (
[height] => 75
[width] => 100
[_content] => http://b.vimeocdn.com/ts/192/593/192593029_100.jpg
)
)
)
)
)
)
)
)
In order to sort by date, you can use the php_function array_multisort(). There is a good example on that page that I think shows what you need. I'll try to provide a better example using your data. Suppose after looping through your albums you end up with an array $myAlbums that looks like this:
Array (
[0] => Array(
[title] => My Title
[description] => some description
[date] 01-05-2011
)
[1] => Array(
.......
)
In order to sort this by date, you could do the following (taken from the example on the php page)
<?php
// Obtain a list of columns
foreach ($myAlbums as $key => $row) {
$date[$key] = $row['date'];
}
// Sort the data with volume descending, edition ascending
// Add $myAlbums as the last parameter, to sort by the common key
array_multisort($date, SORT_DESC, $myAlbums);
?>
Then you can print_r($myAlbums); and you should see that it is sorted. You might have to change the SORT_DESC flag depending on what formate your dates are in. I can't really explain HOW this works, because I'm still trying to figure it out myself... but I think it is what you need.

Categories