Looping through an Array in Php - 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.

Related

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

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.

Properly extracting an embedded array from another array

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

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";
}
}

Check Arrays with different keys?

How do i check if a specific array key exist and how to compare them?
1. Array looks like this.
[33] => Array
(
[211] =>objectr
(
[name] => Test
[id]=> 211
)
)
[23] => Array
(
[311] =>objectr
(
[name] => Tester
[id]=> 311
)
)
2. Array looks like this
[0] => 311
[1] => 211
[2] => 99
Now i need to compare them and get the id of them.
What im looking for is something like that
[0] => Tester
[1] => Test
How do i do that?
array_key_exists - http://php.net/manual/en/function.array-key-exists.php
foreach($first_array as $arr) {
foreach($second_array as $key=>$val)
{
if (array_key_exists($val, $first_array)) {
$final_array[$key] = $arr['name'];
}
}
}
or array_search - http://uk.php.net/array_search
foreach($first_array as $arr) {
foreach($second_array as $val)
{
$key = array_search($val, $arr);
if($key !== false) $final_array[$key] = $arr['name'];
}
}
In both cases you should end up with:
[0] => Tester
[1] => Test
I would transform Array 1 like removing the outer key (at least temporarily) then while iterating through Array 2, i'd compare against transformed Array 1 with array_key_exists.
I hope I understood your question, there might be a language barrier, but here we go:
so basically you have 3 arrays and you want to use the last to to check against the first one to see if those values/keys exists in the first? Well the firs thing you want to do is re structure your first array into something that can easily be translated for checking the values and keys of the next two arrays. so lets call the first array $mapArray:
foreach($mapArray as $mapObject){
foreach($mapObject as $object){
$mapList[$object->id] = $object->name;
}
}
Now this should give us something like:
[211] => 'test'
[311] => 'tester'
So now lets call the 2nd array $arrayIds and the 3rd $arrayNames. To see if am id exists and to get its name when given the array $arrayIds, all you need to do is this:
//given [0] => 311
$keyExists = array_key_exists(311, $mapList); //returns true is the key exists
echo $mapList[311]; //returns tester, the name for the id given
And the other way around:
//given [0] => 'test'
$nameExists = in_array('test', $mapList);
if($nameExists) echo array_search('test', $mapList); // returns 211
hope this is what you are looking for or at least helps you find what you are looking for.
Another approach: We reduce the first array to one dimension:
$first = array();
foreach($first_array as $val) {
$first[key($val)] = current($val);
}
gives:
Array
(
[211] => Array
(
[name] => Test
[id] => 211
)
[311] => Array
(
[name] => Tester
[id] => 311
)
)
(I used an array instead of an object but it works the same).
and then we compute the intersection of the keys:
//assume
$second_array = array(311, 99);
$result = array_intersect_key($first, array_flip($second_array));
which gives:
Array
(
[311] => Array
(
[name] => Tester
[id] => 311
)
)
So it is not quite what you want but you can easily access the name property via $element->name.

Categories