Looping with multidimensional arrays in PHP - php

So I have an Array set up as follows
Array
(
[0] => App\Model\Entity\Member Object
(
[id] => 20
[fname] => John
// ...
[member_attribute] => Cake\ORM\Entity Object
(
[id] => 13
[membership_status] => Active
[last_payment] => 1541581496
// ...
)
)
I'm using a foreach loop for the first level
foreach ($aArray as $Member => $Value)
However I can't access the [member_attributes] data because it's in its own array.
Any help?

The items in your array are objects, so use object notation to access them:
foreach ($aArray as $Member => $Value) {
$id = $Value->member_attribute->id;
}
There also is no need to use the key => value form of the foreach, you could just access your Members like:
foreach ($aArray as $Member) {
$id = $Member->member_attribute->id;
}
That may be a matter of preference, however, I think it is more clear.

Related

Accessing data from DB

I'm getting data from database and putting it in a variable $data. If I'll print_r($data), I'll get something like that:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Bob
)
[1] => stdClass Object
(
[id] => 2
[name] => Mike
)
)
It has more [key] => value in each of them, and obviously it doesn't end on [1].
I'm using foreach() like that:
foreach ($data as $item) {
foreach ($item as $key => $value) {
//code
}
}
I have two question regards all the above:
1) Is there less complex technique to get the $key and $value?
2) If, for example, I want to output only the [name], how would I access it?
The $key[placeholder] while placeholder is a number is outputting the letter number value of the $key.
You have an array with object, so if you want only the name:
$name_list = array();
foreach ($data as $obj) {
$name_list[] = $obj->name;
}
This way you will have an array with only the name of each object.
So to summarize :
You loop through an array of obj, so to access the properties of each object just do :
$obj->/* the properties */;

Why I'm not able to add new key value pair in an associative array?

I've a large associative array titled $data. For your understanding I'm printing below one element from it.
Array
(
[0] => Array
(
[id] => 92
[zip_code] => 07080
[phone_no] => 7327630062
[amount] =>
[currency] => $
[product_details] => Array
(
)
)
[1] => Array
(
[id] => 93
[zip_code] => 07081
[phone_no] => 7327630063
[amount] => 20
[currency] => $
[product_details] => Array
(
)
)
)
Now I want to create a new key-value pair in every element of the above associative array titled $data. For it I wrote following logic but it's not creating a new key-value pair. Can someone please help me in this regard?
foreach($data as $key => $value) {
if(!empty($value['amount'])) {
$value['final_amount'] = $value['amount'] - 2;
} else
$value['final_amount'] = '';
}
From the manual of foreach:
In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by
reference.
foreach($data as $key => &$value)
In the foreach loop, pass the $value by reference by adding an ampersand & before the variable name:
foreach($data as $key => &$value)
This will allow the loop to modify the original $data instead of modifying a copy of it.

Syntax for reading an array in 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'];

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.

Find key of parent in array / PHP

Perhaps someone can help me out with this one:
I'm using a basic search function to find an array deep within an array. The problem is, once that array is found, I'd also like to return it's parent key.
Is there a PHP function that can determine the parent key of an array?
Below is an example of the Search Function... Ideally I'd like to return the array that is found, as well as it's parent key.
function search($array, $key, $value){
$results = array();
if (is_array($array)){
if ($array[$key] == $value){
$results[] = $array;
}
foreach ($array as $subarray){
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
HERE IS AN EXAMPLE TO BETTER ILLUSTRATE WHAT I MEAN:
Here is an example of an array I'd like to search:
Array
(
[categories] => Array
(
[1] => Array
(
[data] =>
[id] => d
[name] => Bracelets
[products] => Array
(
[0] => Array
(
[id] => j
[name] => Red
[data] =>
)
[1] => Array
(
[id] => gi
[name] => Torqoise
[data] =>
)
)
)
If I search for something with the 'id' of "j", I would get this array as the result:
Array
(
[0] => Array
(
[id] => j
[name] => Red
[data] =>
)
)
Now, ideally I would also like to know the parent key of this Array, which in the example is 'Products', which I obviously would need to retrieve before returning the results...
No, there is no built in function. You can pass parent key in the function params
You could use array_flip() to swap the key and values so you can retrieve the key with the value.
You could also slightly modify your foreach to something like
foreach ($array as $subarray_key => $subarray){
$results = array_merge($results, search($subarray, $key, $value));
}
and $subarray_key would be the key.

Categories