Properly extracting an embedded array from another array - php

I am trying to extract an array embedded in another array using the standard foreach loop, the problem is it keep returning unwanted data.
Array
Array
(
[id] => 2035443879
[status] => Unshipped
[sku] => 0340024275-UsedGood
[isbn] => 0340024275
[condition] => Used
[number_of_items] => 1
[title] => Linnets and Valerians (Knight Books)
[purchase_date] => 1361536149
[0] => Array
(
[status] => Shipped
[title] => Linnets and Valerians (Knight Books)
[date] => 1361491200
)
)
Print function
function mapStatus($orders){
foreach($orders as $order){
echo "<pre>";
print_r($order);
echo "</pre>";
foreach(array_unique($order) as $item){
echo "-".$item["status"]."-";
}
}
}
Outcome
-2--U--0--0--U--1--W--L--H--1--Shipped-
As you can see from my outcome what was printed is not exactly what I expected, it seems that I am printing the first character of every index in the array and not just the actual array I want.
I'm aware that I can use a is_array() function to determine if what I am printing is coming from an array object but I would like to know if there is proper way to do what I want?

for ($i = 0; $i < $order['number_of_items']; $i++) {
echo "-".$order[$i]["status"]."-";
}
However, I recommend a different data structure. Instead of having the items as indexed elements within the order array, you should have $order['items'], which points to an array. Then you can use:
foreach ($order['items'] as $item)
Then you don't need $order['number_of_items'], you can just use count($order['items']).

Related

foreach loop nested array json php

How do I loop through the array to get the "converted_amount" values?
stdClass Object
(
[rows] => Array
(
[0] => stdClass Object
(
[components] => Array
(
[0] => stdClass Object
(
[amount] => 5033298.132349431
[count] => 1337
[rate] => 3.1398800
[converted_amount] => 1603021.9952863243
)
[1] => stdClass Object
(
[amount] => 458673.0026585825
[count] => 325
[rate] => 0.45260800
[converted_amount] => 1013400.4157520011
)
I have tried a foreach like this but it doesn't work. I think there should be something in-between components and converted_amount - maybe another foreach? I'm not sure.
foreach ($getexvolume as $vol) {
echo $vol['rows'][0]['components']['converted_amount'];}
You have an object instead if array. You must work with data as an object...
foreach ($getexvolume->rows as $row) {
foreach ($row->components as $component) {
echo $component->converted_amount;
}
}
echo $vol->rows[0]->components[0]->converted_amount;
You are mixing array and object. Your output is an object so you have to access it like one otherwise if you want to treat it like an array you have to convert it to an array. As for now you can use the above code.
A better solution which i think fits your problem is that you loop around your nested array like:
foreach($vol->rows[0]->components as $data){
echo $data->converted_amount;
}
Try this:
foreach ($getexvolume->rows[0]->components as $vol) {
echo $vol->converted_amount;
}
The object you have is a mix of Arrays and Objects.
Arrays can be addressed as $array['value'] but Objects must be addressed as $object->value.
echo $vol->rows[0]->components[0]->converted_amount;
However since you have multiple components, you will need a nested loop:
foreach ($getexvolume as $vol)
{
foreach($vol->rows as $row)
{
foreach($row->component as $component)
{
echo $component->converted_amount;
}
}
}
(pseudocode - not tested).
Ideally the variable would be normalised as a multidimensional array or nested object first so you don't have to worry about syntax.

Looping through JSON output from Hubspot deals API

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

Looping through an Array in Php

Can't seem to figure this out. I struggle so badly with arrays. I am trying to get the data out of this array and keep getting errors.
I tried using this code below and several other attempts and failed miserably. What's the best way to remember how to do this? Everytime I don't code Php for a couple months I seem to forget everything...
foreach( $data as $key) {
foreach( $key as $value => $sum) {
echo $sum;
}
}
Array
(
[result] => OK
[data] => Array
(
[destination] =>
[tracking] => Array
(
[0] => Array
(
[loc] => Array
(
[city] =>
[territory] => ME
[country] => US
)
[desc] => Delivered
[stamp] => 1384977300
[time] => 11/20/13 11:55 am
[locStr] => ME, US
[geo] => Array
(
[lat] => 45.253783
[lon] => -69.4454689
)
)
iterate through tracking?
if ($arr['result'] == "OK") {
for ($i=0; $i < count( $arr['data']['tracking'] ); $i++) {
// do stuff with $arr['data']['tracking'][$i]
}
}
In php there are basically two different type of arrays. key/value based array and element based array.
An element based array is
$arr = array("a", "b", "c");
echo $arr[0]; // prints a
echo $arr[2]; // prints c
// hash - k/v array
$arr = array("monkey" => "banana", "chicken" => "egg");
echo $arr["monkey"]; // prints banana
// combination
$arr = array( array("monkey" => array("banana", "water")));
echo $arr[0]["monkey"][1]; // prints water
hope this helps.
I think your code is not wrong. you have three dimensional array. you have only two foreach. you have to loop within a loop within a loop. and if you try to echo an array Ofcourse you will have an error so you should check first if that output is an array or not.

Renaming the keys in multidimensional associate arrays

I have searched SO and Google and have found lots of similar questions, but nothing that fits my exact use case.
I have an array of arrays like this:
Array
(
[0] => Array
(
[id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
[date_entered] => 10/01/2013 03:38pm
)
[1] => Array
(
[id] => 176815c6-b57f-7643-0f08-524b4f22b51c
[date_entered] => 10/01/2013 03:42pm
)
[2] => Array
(
[id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
[date_entered] => 10/02/2013 11:56am
)
)
I need to rename the keys of the first dimension to be the value of the date_entered key in the second dimension arrays like this so that I can (hopefully) sort the array by the most recent date. I need to preserve the contents of each array because I will need to grab the ID that corresponds to the correct date.
Array
(
[10/01/2013 03:38pm] => Array
(
[id] => c80c5133-1140-8187-ad3b-524b4ed0f1a8
[date_entered] => 10/01/2013 03:38pm
)
[10/01/2013 03:42pm] => Array
(
[id] => 176815c6-b57f-7643-0f08-524b4f22b51c
[date_entered] => 10/01/2013 03:42pm
)
[10/02/2013 11:56am] => Array
(
[id] => df0f8824-0b12-b92e-1d2e-524c6cb19c41
[date_entered] => 10/02/2013 11:56am
)
)
I am trying to do it like this (which is obviously not correct) but for the life of me I still can't get it.
foreach ($array as $key) {
foreach ($key as $subkey => $subvalue) {
if ($subkey == 'date_entered') {
// change the name of the key?
}
}
}
I am really struggling with multidimensional arrays and manipulating them, no matter how much I read and practice! Can anyone help?
This code should do it:
$newArray = array();
foreach ($array as $id => $dataset) {
$newArray[ $dataset['date_entered'] ] = $dataset;
}
I created a new array here because "changing the array within a foreach loop may lead to unexpected behaviour" (source).
If you really need to preserve your original array, you can use your numeric indices for accessing the elements:
$arrCount = count($array);
for ($i=0; $i<$arrCount; $i++) {
$array[ $dataset['date_entered'] ] = $array[$i];
unset($array[$i]);
}
All elements get copied before they get unset/deleted at the previous key.

Printing Our Array Data

In PHP, Codeigniter: my array, $phoneList, contains the following:
Array
(
[name] => One, Are
[telephonenumber] => 555.222.1111
)
Array
(
[name] => Two, Are
[telephonenumber] => 555.222.2222
)
Array
(
[name] => Three, Are
[telephonenumber] => 555.222.3333
)
How do I list each name out? Each number out? Am I right in saying my array contains three different Arrays? And is that normal, for an array to contain arrays?
When I do a print_r($phoneList), I get the following:
Array ( [0] => Array ( [name] => One, Are [telephonenumber] => 555.222.1111 ) [1] => Array ( [name] => Two, Are [telephonenumber] => 555.222.2222 ) [2] => Array ( [name] => Three, Are [telephonenumber] => 555.222.3333 ) )
You'll probably want to use foreach to loop through them. Something like this:
foreach($data as $arr) { // assuming $data is the variable that has all this in
echo $arr['name'].": ".$arr['telephonenumber']."<br />";
}
Here is the solution. Foreach is the easiest approach.
It's completely normal to have an array of arrays (in this case an array of associative arrays). They can be written like so:
$arrayofarray = array(array('name' => 'aname', 'phone'=>'22233344444'), array('name' => 'bobble', 'phone'=>'5552223333'));
print_r($arrayofarray);
and you should be able to print out the content in this way:
foreach ($arrayofarray as $arr){
print $arr['name']."\n";
print $arr['phone']."\n";
}
If you want to know what terms are set in each associative array you can use array_keys() to return them (as a simple array). For example:
foreach ($arrayofarray as $arr){
$setterms=array_keys($arr);
foreach ($setterms as $aterm){
print "$aterm -> ".$arr[$aterm]."\n";
}
}

Categories