I'm working with the S3 library found here: http://undesigned.org.za/2007/10/22/amazon-s3-php-class/
It works great, but I'm having a tough time extracting the data I need from the returned array results. I'm grabbing the bucket contents, and it returns something like this:
Array (
[sample_mpeg4.mp4] => Array (
[name] => sample_mpeg4.mp4
[time] => 1378922417
[size] => 245779
[hash] => dc77a8de8c091c19d86df74eb7
)
[steve.jpg] => Array (
[name] => steve.jpg
[time] => 1381270899
[size] => 61109
[hash] => a008368bf58515775c45e75c54
)
[stev-small-photo1.png] => Array (
[name] => stev-small-photo1.png
[time] => 1381270891
[size] => 680353
[hash] => ddcb22a103d4fa8360083ad70a
)
)
Ok, cool. I'm querying and matching the key to pull out specific info on that particular piece of media. My code for that looks like this:
$searchVar = "steve.jpg";
$s3 = new S3(awsAccessKey, awsSecretKey);
$bucket_contents = $s3->getBucket("uploads.bucket.com");
//fetch array of current files
$searchAssetsBucket = array_keys($bucket_contents);
foreach ($searchAssetsBucket as $value) {
if($value == $searchVar) {
echo $value['time'];
}
}
if(empty($returnValue)) {
$returnValue = "Sorry no results for <b>$searchVar</b>.";
}
This doesn't work for me. What I'm really trying to do is get the code to return the name/time/size/hash vars from the [steve.jpg] array once it's been matched. I'm not sure what I'm doing wrong here, but this code simply returns "s".
Does anyone have any ideas? I'm truly at a lose here...
I would do something like this:
$myArray=$yourOriginalS3Array;
$searchVar='Steve.jpg';
// set up default/blank data in $matchedArr
foreach ($myArray as $key => $val)
{
if($key == $searchVar) {
$matchedArr=$val;
}
}
echo "The name is ".$matchedArr['name']." and the size is ".$matchedArr['size']."<br>";
This way, you are checking the keys of your original array, and if matched, returning an array that matches the second level of the original array which can be easily accessed in your code.
Related
I am trying to use the Hubspot API (http://developers.hubspot.com/docs/overview) to loop through all deals and find only those which are current and then do something with those deals.
No matter what I try to do I cannot get my head around how I access the data I need - below is an example of the output.
In the API there are lots of items like dealstage below and the value field under these is what I need to access - for example in this case the deal is closedlost. Another example would be amount which would also have an entry in value so I can then see the deal value.
I want to loop through all deals and for each deal get the dealstage, amount, last update, owner and so on. Each of these are contained in an array of the same layout as [dealstage] below with a value
I have gotten to where I can print the dealstage value for each deal but it doesn't really help - is there a better way of doing this?
foreach ($list['deals'] as $line) {
foreach ($line['properties'] as $row => $value) {
if ($row=="dealstage") {
$stage=$value['value'];
print $stage."<br>";
}
}
}
Example array:
Array
(
[deals] => Array
(
[0] => Array
(
[portalId] => 12345
[dealId] => 67890
[isDeleted] =>
[associations] => Array
(
[associatedVids] => Array
(
[0] => 4051
)
[associatedCompanyIds] => Array
(
[0] => 23456
)
[associatedDealIds] => Array
(
)
)
[properties] => Array
(
[dealstage] => Array
(
[value] => closedlost
)
[createdate] => Array
(
[value] => 1471334633784
)
[amount] => Array
(
[value] => 1000
)
Would something like this be what you are looking for. Loop through the array picking out the items you are interested in and place them in a nice simple array for you to use later when building your email.
$for_email = array();
foreach ($list['deals'] as $line) {
$t = array();
if (isset($line['properties']['dealstage']['value'])) {
$t['dealstage'] = $line['properties']['dealstage']['value'];
}
if (isset($line['properties']['amount']['value'])) {
$t['amount'] = $line['properties']['amount']['value'];
}
if (isset($line['properties']['createdate']['value'])) {
$t['createdate'] = $line['properties']['createdate']['value'];
}
// any other data you want to capture
// put this data in the new array
$for_email[] = $t;
}
// check what the new array looks like
print_r($for_email);
I want to be able to display the multidimensional associative array in a table. The arrays are created by Solarium API which is used for debugging any indexing issues. Each array has different number of arrays and keys.
I want it keep it in a way that it works with any number or arrays and keys. I started with using a foreach loop but I'm stuck at this point. How would I go about doing this?
Code I have so far:
foreach ($metadatas as $metadata) {
foreach($metadata as $type => $data) {
echo '<tr>';
echo '<td>'.$type.'</td>';
echo '<td>'.$data.'</td>';
echo '</tr>';
}
}
This is the array I get using print_r():
Solarium\QueryType\Extract\Query Object
(
[options:protected] => Array
(
[handler] => update/extract
[resultclass] => Solarium\QueryType\Extract\Result
[documentclass] => Solarium\QueryType\Update\Query\Document\Document
[omitheader] =>
[extractonly] =>
[uprefix] => ignored_
[commit] => 1
[file] => http://url.com/branch/files/2015/03/Client-Feedback-Form.doc
[document] => Solarium\QueryType\Update\Query\Document\Document Object
(
[boost:protected] =>
[modifiers:protected] => Array
(
)
[key:protected] =>
[fieldBoosts:protected] => Array
(
[id] =>
[site] =>
[description] =>
[url] =>
[title] =>
)
[version:protected] =>
[helper:protected] => Solarium\Core\Query\Helper Object
(
[placeHolderPattern:protected] => /%(L|P|T|)([0-9]+)%/i
[assembleParts:protected] =>
[derefencedParamsLastKey:protected] => 0
[query:protected] => Solarium\QueryType\Update\Query\Document\Document Object
*RECURSION*
)
[filterControlCharacters:protected] => 1
[fields:protected] => Array
(
[id] => 227-7653
[site] => Branch Name
[description] =>
[url] => http://url.ca/branch/files/2015/03/Client-Feedback-Form.doc
[title] => Client Feedback Form
)
)
)
[fieldMappings:protected] => Array
(
[content_type] => type
[author] => authors
[last_modified] => lastModifiedDate
[creation_date] => creationDate
[content] => content
)
[helper:protected] =>
[params:protected] => Array
(
)
)
I need more fake internet points to comment. So instead you get my poor answer. I'd try some sort of recursive function calling.
function someFunction($table , $array){
foreach($array as $key => $value){
if(is_array($value)){
someFunction(&$table, $value)
}
else {
//Add to your existing $table
}
}
return $table;
}
$table = someFunction("" , array());
obviously this is super simplistic view. But the idea is to keep passing your table deeper and deeper into the array. And eventually it will fall back out as you stop running into new arrays. I did something similar a while back passing around a DOMDocument() to build a super complex XML.
But this is only really useful when you don't know the possible size or depth of an array. If your array has keys, even if it's multidimensional, that you know will or won't exist and how deep they go. It's probably better to follow the answer in your comments and just build a nice HTML page.
Good luck.
As you can see from the first line of your output, it is not an array, but an OBJECT! And as you see in [options:protected] , it is protected variable, so you cannot access it from external foreach loop.
What you can do, is to declare a loop function inside that class:
class Query{
....
....
public function iterate(){
foreach ($this->options as $metadata) {
foreach($metadata as $type => $data) {
echo '<tr>';
echo '<td>'.$type.'</td>';
echo '<td>'.$data.'</td>';
echo '</tr>';
}
}
}
}
And then call it outside the class:
$object->iterate();
You can read more about this here: http://php.net/manual/en/language.oop5.iterations.php
I have an array, stored in $array, that with
print "<pre>";
print_r($array);
print "</pre>";
gives an output like this:
Array
(
[device] => Array
(
[0] => Array
(
[#attributes] => Array
(
[name] => Low volt light
[id] => 10
[type] => Z-Wave Switch Multilevel
[value] => 0
[address] => 00016922-018
[code] =>
[canDim] => True
[lastChange] => 26-07-2014 17:31:33
[firstLocation] => Kitchen
[secondLocation] => Main
)
)
[1] => Array
(
[#attributes] => Array
(
[name] => Light
[id] => 11
[type] => Z-Wave Switch Multilevel
[value] => 99
[address] => 00016922-019
[code] =>
[canDim] => True
[lastChange] => 31-07-2014 20:01:05
[firstLocation] => Bedroom
[secondLocation] => Main
)
)
I cannot find my way to access/display for example the value (in this case 0) of device with [id]=>10. What syntax would be the right one in php?
There's not an easy way to do this, without looping through the array.
e.g.
foreach ($array['devices'] as $device) {
if ($device['#attributes']['id'] === $idBeingSearchedFor) {
// Do something with $device.
}
}
Due to the #attributes array key, I'm guessing that this came from XML at some point: You might consider using Simple XML to parse it instead, as you could potentially use XPath then, which does support this type of access.
Alternatively again, you could reformat the array so it could be easily accessed by ID.
For example:
$formattedArray = array();
foreach ($array['devices'] as $device) {
$id = $device['#attributes']['id'];
$formattedArray[$id] = $device;
}
You could then access the device by its ID as follows:
$device = $formattedArray[$idBeingSearchedFor];
You could do it like that:
$id = 10;
$device = array();
foreach($array['device'] as $devices) {
if($devices['#attributes']['id'] == $id) {
$device = $devices['#attributes'];
break;
}
}
echo $device['value'];
Looks like SimpleXML, and if that is the case then those arrays are actually objects that, when put through print_r, look just like arrays. To access them, do the following:
Get straight to the data:
$name = $array->device[0]->attributes()->name;
Or loop through each of the attributes in the first device:
foreach ($array->device[0]->attributes() as $key => $value) {
// Do something with the data. $key is the name of the
// attribute, and then you have the $value.
}
Or you could loop through all the devices:
foreach ($array->device as $device) {
foreach ($device->attributes() as $key => $value) {
// Do something
}
}
It's simple ... try below...
print $array['device'][0]['#attributes']['id'];
or
print $array['device']['0']['#attributes']['id'];
First time Ive posted on here..
So Im new to php, mysql and JSON, and Im having some issues, I may just be approaching the problem in the incorrect way, so let me know what you think.
Basically there's a website that I'm trying to do that has some info located on another server, I fetch that info with JSON.
Here is the code:
//Start of JSON Main Content Fetch + Main Content Render
//JSON send_recv of menu array. Assign results to $main_content_b_render
$main_content_fetch=send_recv("menu", array("id" => "17", "fetchContent" => TRUE));
//Renders menu from JSON results.
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
print_r($main_content_fetch);
}
render_main_content($main_content_fetch['results']);
?>
What I can actually get from the other server is the following:
Array ( [id] => 17 [name] => Accessories [reference] => [content] => Array ( [0] => Array ( [type] => Heading1 [content] => BLAH BLAH BLAH TXT TXT TXT [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accblurb ) [1] => Array ( [type] => Image [align] => Left [image] => http://URL.../image/43/webcontent/accshop11.jpg [thumb] => http://URL....com.au/image/thumb/100x100/43/webcontent/accshop11.jpg [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accshop1.jpg ) ) )
I can assign the array values to a variable but it will only assign the first ones, so for example:
if i put this in the function and echo it out
$id = $main_content_fetch['content'];
echo $id;
all I get back is 'Array', what I actually want is the 'BLAH BLAH BLAH TXT TXT TXT' thats located later in the returned info, we actually everything thats located in the last set of brackets...
( [type] => Heading1 [content] => BLAH BLAH BLAH TXT TXT TXT [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accblurb ) [1] => Array ( [type] => Image [align] => Left [image] => http://URL.../image/43/webcontent/accshop11.jpg [thumb] => http://URL....com.au/image/thumb/100x100/43/webcontent/accshop11.jpg [scope] => DetailAndThumb [active] => 1 [reference] => [name] => accshop1.jpg )
What I want to do is to be able to assign basically everything I get back to a variable, as it is. because I think Ill be able to pick what I want out easily enough.. and I don't know of any other way to do it :/
Sorry if its a bit vague, Not very good at explaining myself, but I hope someone can workout what I'm talking about and help.
This is your function. I just replaced print_r with return
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
return $main_content_fetch;
}
lets say you call this function like this. Now you can assign the array in individual variable this way
$data = render_main_content($parameter);
$id = $data['id'];
$name = $data['name'];
......
Hope this helps you. All you need is assign array variable with index to the variable you wish.
sorry, just figured out you have nested array, why not access the required item by $main_content_fetch["content"][0]["content"]?
Anyway by print_r($arr, TRUE) you can print the actual items and see the structure of the array you're dealing .
If I understood you correctly, in order to get the BLA BLA BLA text your code should look like this:
//Start of JSON Main Content Fetch + Main Content Render
//JSON send_recv of menu array. Assign results to $main_content_b_render
$main_content_fetch=send_recv("menu", array("id" => "17", "fetchContent" => TRUE));
//Renders menu from JSON results.
function render_main_content($main_content_fetch)
{
//Start of processing $menu_result
$main_content_b_render = $main_content_fetch['content'];
//return the second level "content"
return $main_content_b_render[0]['content'];
}
$content = render_main_content($main_content_fetch['results']);
print $content;
?>
You can use something like
foreach (array_expression as $key => $value ) {
// TODO - probably need a recursive version
$$key = $value;
}
When traversing the array, that statement allows you to create new variables in the code.
But, as a rule, you should never rely on the format of the output you get from the other server. My recommendation would be to explicitly extract the information you need from the input, rather just taking it as is and importing it in.
So for example, you would do
$id = input['id'];
You can then check if everything got assigned properly and catch any errors.
You can use below php code solve this issue
$value) { $$key = $value; }
//or....
foreach($user as $key=>$value) { ${$key} = $value; }
?>
First use print_r($arr, TRUE) to print your array when debugging, that will help you a lot :-) (don't forget the TRUE flag!).
You can access any item in the array as you did, but it looks like you're printing $main_content_fetch instead of $main_content_b_render?
I have an array which is generated from an XML file and it shows me like below when printed with print_r
Array
(
[cxname] => Global CX 87 123
[ipaddress] => 66.240.55.87
[slots] => Array
(
[slot] => Array
(
[0] => Array
(
[slotno] => 1
[cardtype] => 0x24
[modelno] => OP3524J
[label1] => OP
[label2] => Module
[severity] => Minor
)
[1] => Array
(
[slotno] => 2
[cardtype] => 0x25
[modelno] => OP3524K
[label1] => OP
[label2] => Module
[severity] => Major
)
)
)
)
When I print like this, it shows nothing
echo $dataArray->cxname;
But following code works and prints "Global CX 87 123 "
echo $dataArray["cxname"];
How can I make it work as above example.
Just do this:
$dataArray = (object)$dataArray;
It'll convert the array in an stdClass object and allow you to use it that way. Please note that this will only convert the first level for the array. You'll have to create a function to recurse through the array if you want to access all levels that way. For example:
<?php
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
For more information, have a look at http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass. To find out about typecasting, you can also read http://www.php.net/manual/en/language.types.object.php#language.types.object.casting.
This:
echo $dataArray["cxname"];
is the way you access array elements. But this:
echo $dataArray->cxname;
is the way, you access class members.
If you want to access the data as class members, you have to use a xml parser which returns classes (or objects), not arrays.
If you have got the XML string, you can parse it into an object by using simplexml_load_string().