Find key of parent in array / PHP - 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.

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

How to combine 2 arrays based on same value of same key

I want to merge/combine 2 arrays based on the same key/value pair.
To be more clear, what I'm searching for is kind of a join function known in MySQL. The first array should be "joined" by the second one, based on the ID, which is the key/value pair 'name'.
How can I do this?
1. ARRAY
[0] => Array
(
[name] => first
[logo] => url
[cat] => abc
)
[1] => Array
(
[name] => second
[logo] => url
[cat] => abc
)
2. ARRAY
[0] => Array
(
[name] => first
[menu] => true
[key] => value
)
NEW ARRAY (Expexted Result):
[0] => Array
(
[name] => first
[logo] => url
[cat] => abc
[menu] => true
[key] => value
)
As you an see, it's quite self-explaining. In this case, the 'name' key is like an ID (for both arrays).
If you reindex your second array by name first, it will be easier to get those values from it.
$second = array_column($second, null, 'name');
(It's okay to do this if 'name' is unique in the array. I assume that's the case since you said it's "like an ID". If 'name' isn't unique then you'll lose some rows when you reindex, because array keys have to be unique.)
Then iterate your first array and merge any corresponding values in the second array into the result.
foreach ($first as $key => $value) {
if (isset($second[$value['name']])) {
$result[$key] = array_merge($value, $second[$value['name']]);
}
}
This would be like an inner join in SQL, where the result would only include rows where the value exists in both tables. If you wanted it to work more like a left join, then you'd need to merge a set of empty values for the keys in the second array if a matching name value wasn't found there.
foreach ($first as $key => $value) {
if (isset($second[$value['name']])) {
$result[$key] = array_merge($value, $second[$value['name']]);
} else {
$result[$key] = array_merge($value, ['menu' => null, 'key' => null]);
}
}
Working example at 3v4l.org.
Try this
$mergedArray = array_merge_recursive ($firstArray,$secondArray);
$newArray = [];
foreach( $mergedArray as $subArr ) {
$newArray = array_merge($subArr,$newArray);
}

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.

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