Renaming the keys in multidimensional associate arrays - php

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.

Related

Array values to single array using foreach loop in PHP

I am working with php and arrays, I have multiple arrays like following
Array
(
[0] => Array
(
[wallet_address] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[1] => Array
(
[wallet_address] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[2] => Array
(
[wallet_address] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
and so on....
And i want to make them in single array with comma like following way
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
How can i do this ?Here is my current code but not working,showing me same result(0,1,2 keys),Where i am wrong ?
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[]=$arr;
}
echo "<pre>";print_R($set);
The original array is an Assoc array and therefore the wallet_address needs to be addressed specifically in a loop. Or you could use the array_column() builtin function to achieve the same thing.
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[] = $arr['wallet_address'];
}
echo "<pre>";print_r($set);
Or
$new = array_column($GetUserFollower, 'wallet_address');
print_r($new);
RESULT
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
Your comments are making me think you want an array without a key, which is impossible. If you do this with the example you show in your comments
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
print_r($set);
You will see
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)

Search part of array key on PHP

I have the following output when printing an array called yestardayArray using print_r:
Array
(
[project-id] => Array
(
[373482] => Array
(
[responsible-ids] => Array
(
[171812,129938] => Array
(
[0] => Array
(
[task-id] => 18055196
[content] => HU-002
[responsible-ids] => 171812,129938
)
)
[171812] => Array
(
[0] => Array
(
[task-id] => 18055300
[content] => HU-002
[responsible-ids] => 171812
)
[1] => Array
(
[task-id] => 18055307
[content] => HU-002 - BACK
[responsible-ids] => 171812
)
)
)
)
)
)
I'm iterating througth project-id (using the variable $pid), in the case of this example "373482", and also iterating througth responsible-ids with $key. As $key i'm using all the posible responsible-ids values for the project to get a match and do some stuff.
That work great in the case that there is only one responsible (because there is a full match), but if there are more, like in "171812,129938" there is no match.
How would you validate if $key (171812 or 129938) is part of responsible-ids ("171812,129938")?
I tried to convert the array key to a string, in order to use built-in php search functions like substr_count or strpos.
$needString = $yesterdayArray["project-id"][$pid]["responsible-ids"][$key];
But when I print needString I get "Array" instead of "171812,129938".
What can I do?
Call explode() on the keys, and then use in_array() to check if $key is in the array.
foreach ($yesterdayArray["project-id"] as $pid => $project) {
foreach ($project["responsible-ids"] as $resp_ids => $tasks) {
$resp_id_array = explode(',', $resp_id);
if (in_array($key, $resp_id_array)) {
// do something
}
}
}

Organize multidimensional array using Recursion

I have an array that I've build dynamically. It has many nested arrays because of the way it's built, but the depth is useless to me, so I organize it right afterwards. It could look like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
)
)
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
I want to almost-flatten this array (i.e. access its data using $array[$i]['cost'] on all entries, regardless if they were nested deep before I processed them). So far I've been using SPL recursion, with something along these lines:
function flatten($array) {
$return = array();
$it = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $value) {
if(isset($value['cost'])) {
$return[] = $value;
}
}
return $return;
}
It works for the most part, but some of the values in the original array, which do have a 'cost' index in them, fail to be added to the new array because they are passed as nested arrays themselves, like so:
Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
...instead of just (which most of the time I get):
Array
(
[index] => -1
[cost] => 0.189956571618
)
I thought the whole point of using a RecursiveIterator was to go deep within the array and fetch the entries which don't have arrays within them (i.e. the 'values' I want). Am I using the wrong tools for this job? If so, what would be more appropriate to loop through an array for which I don't know the depth? If SPL is the way to go, what am I doing wrong?
Thanks in advance.
you could use array_walk_recursive
EDIT
function flatten($array) {
$return = array();
array_walk_recursive($array, function($value, $key) use (&$return) {
if(isset($value['cost']) $return[] = $value;
});
return $return;
}
on the SPL part EDIT long discussion in the chatroom, check OP's answer

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

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