I am trying to create a function to remove keys from a dynamic multidimensional array, i need to give:
removeByIndex(['hello', 'my', 'world']);
And then the function needs to do this:
unset($array['hello']['my']['world']);
The number of indexes are dynamic, example:
removeByIndex(['hello', 'my']); // Do: unset($array['hello']['my']);
removeByIndex(['hello']); // Do: unset($array['hello']);
I tried to use some foreach loops, but i didn't find a solution yet.
Any help will be welcome.
No need for eval() with a little bit of referencing.
/**
* Remove index from multi-dimensional array.
*
* #param array $array
* The array to remove the index from.
* #param array $indices
* Indexed array containing the indices chain up to the index that should be
* removed.
* #return
* The array with the index removed.
* #throws \InvalidArgumentException
* If the index does not exist within the array.
*/
function removeByIndex(array $array, array $indices) {
// Create a reference to the original array.
$a =& $array;
// Count all passed indices, remove one because arrays are zero based.
$c = count($indices) - 1;
// Iterate over all passed indices.
for ($i = 0; $i <= $c; ++$i) {
// Make sure the index to go down for deletion actually exists.
if (array_key_exists($indices[$i], $a)) {
// This is the target if we reached the last index that was passed.
if ($i === $c) {
unset($a[$indices[$i]]);
}
// Make sure we have an array to go further down.
elseif (is_array($a[$indices[$i]])) {
$a =& $a[$indices[$i]];
}
// Index does not exist since there is no array to go down any further.
else {
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
}
// Index does not exist, error.
else {
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
}
return $array;
}
print_r(removeByIndex(
[ "test1" => [ "test2" => [ "test3" => "test" ] ], "test4" => "test" ],
[ "test1", "test2", "test3" ]
));
Since I mentioned it in the comments, one could (micro-)optimize the function, but I advice against it, since it is less readable and might confuse some programmers.
<?php
function removeByIndex(array $array, array $indices) {
$a =& $array;
$c = count($indices) - 1;
$i = 0;
do {
if (array_key_exists($indices[$i], $a)) {
if ($i === $c) {
unset($a[$indices[$i]]);
return $array;
}
elseif (is_array($a[$indices[$i]])) {
$a =& $a[$indices[$i]];
}
else break;
}
else break;
}
while (++$i);
throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
Based on the briliant #Fleshgrinder answer, i am using this final version:
function removeByIndex($vars, $indexes) {
if ( ! is_array($indexes)) {
throw new \Exception('Array expected');
}
$array = & $vars;
$qtd_indexes = count($indexes);
for ($i = 0; $i < $qtd_indexes; $i++) {
if ( ! array_key_exists($indexes[$i], $array)) {
throw new \Exception($indexes[$i] . " doesn't exist");
}
// Check if it is the target entry
if ($i === $qtd_indexes - 1) {
unset($array[$indexes[$i]]);
} elseif (is_array($array[$indexes[$i]])) { // Check if exists one more level
$array = & $array[$indexes[$i]];
} else {
// If it isn't the target and it isn't an array, throw exception
throw new \Exception("Content of '" . $indexes[$i] . "' isn't an array");
}
}
return $vars;
}
I was researched for a couple of hours for this solution, nowhere found an optimal solution. so, i wrote it by myself
function allow_keys($arr, $keys)
{
$saved = [];
foreach ($keys as $key => $value) {
if (is_int($key) || is_int($value)) {
$keysKey = $value;
} else {
$keysKey = $key;
}
if (isset($arr[$keysKey])) {
$saved[$keysKey] = $arr[$keysKey];
if (is_array($value)) {
$saved[$keysKey] = allow_keys($saved[$keysKey], $keys[$keysKey]);
}
}
}
return $saved;
}
use: example
$array = [
'key1' => 'kw',
'loaa'=> ['looo'],
'k' => [
'prope' => [
'prop' => ['proo', 'prot', 'loolooo', 'de'],
'prop2' => ['hun' => 'lu'],
],
'prop1' => [
],
],
];
call: example
allow_keys($array, ['key1', 'k' => ['prope' => ['prop' => [0, 1], 'prop2']]])
output:
Array ( [key1] => kw [k] => Array ( [prope] => Array ( [prop] => Array ( [0] => proo [1] => prot ) [prop2] => Array ( [hun] => lu ) ) ) )
so you get only needed keys from the multidimensional array. it is not limited only for "multidimensional", you can use it by passing an array like
['key1', 'loaa']
output you get:
Array ( [key1] => kw [loaa] => Array ( [0] => looo ) )
i'm writing it here for reason that this topic is one of the first when you type on google
recursive remove keys multidimensional php
hope someone helps this one, as i searched a lot, and nothing found.
cheers!
Related
This question already has answers here:
PHP rename array keys in multidimensional array
(10 answers)
Closed last month.
When I var_dump on a variable called $tags (a multidimensional array) I get this:
Array
(
[0] => Array
(
[name] => tabbing
[url] => tabbing
)
[1] => Array
(
[name] => tabby ridiman
[url] => tabby-ridiman
)
[2] => Array
(
[name] => tables
[url] => tables
)
[3] => Array
(
[name] => tabloids
[url] => tabloids
)
[4] => Array
(
[name] => taco bell
[url] => taco-bell
)
[5] => Array
(
[name] => tacos
[url] => tacos
)
)
I would like to rename all array keys called "url" to be called "value". What would be a good way to do this?
You could use array_map() to do it.
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
Loop through, set new key, unset old key.
foreach($tags as &$val){
$val['value'] = $val['url'];
unset($val['url']);
}
Talking about functional PHP, I have this more generic answer:
array_map(function($arr){
$ret = $arr;
$ret['value'] = $ret['url'];
unset($ret['url']);
return $ret;
}, $tag);
}
Recursive php rename keys function:
function replaceKeys($oldKey, $newKey, array $input){
$return = array();
foreach ($input as $key => $value) {
if ($key===$oldKey)
$key = $newKey;
if (is_array($value))
$value = replaceKeys( $oldKey, $newKey, $value);
$return[$key] = $value;
}
return $return;
}
foreach ($basearr as &$row)
{
$row['value'] = $row['url'];
unset( $row['url'] );
}
unset($row);
This should work in most versions of PHP 4+. Array map using anonymous functions is not supported below 5.3.
Also the foreach examples will throw a warning when using strict PHP error handling.
Here is a small multi-dimensional key renaming function. It can also be used to process arrays to have the correct keys for integrity throughout your app. It will not throw any errors when a key does not exist.
function multi_rename_key(&$array, $old_keys, $new_keys)
{
if(!is_array($array)){
($array=="") ? $array=array() : false;
return $array;
}
foreach($array as &$arr){
if (is_array($old_keys))
{
foreach($new_keys as $k => $new_key)
{
(isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
$arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
unset($arr[$old_keys[$k]]);
}
}else{
$arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
unset($arr[$old_keys]);
}
}
return $array;
}
Usage is simple. You can either change a single key like in your example:
multi_rename_key($tags, "url", "value");
or a more complex multikey
multi_rename_key($tags, array("url","name"), array("value","title"));
It uses similar syntax as preg_replace() where the amount of $old_keys and $new_keys should be the same. However when they are not a blank key is added. This means you can use it to add a sort if schema to your array.
Use this all the time, hope it helps!
Very simple approach to replace keys in a multidimensional array, and maybe even a bit dangerous, but should work fine if you have some kind of control over the source array:
$array = [ 'oldkey' => [ 'oldkey' => 'wow'] ];
$new_array = json_decode(str_replace('"oldkey":', '"newkey":', json_encode($array)));
print_r($new_array); // [ 'newkey' => [ 'newkey' => 'wow'] ]
This doesn't have to be difficult in the least. You can simply assign the arrays around regardless of how deep they are in a multi-dimensional array:
$array['key_old'] = $array['key_new'];
unset($array['key_old']);
You can do it without any loop
Like below
$tags = str_replace("url", "value", json_encode($tags));
$tags = json_decode($tags, true);
class DataHelper{
private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
foreach ($map as $old => $new) {
$old = preg_replace('/([\.]{1}+)$/', '', trim($old));
if ($new) {
if (!is_array($new)) {
$array[$new] = $array[$old];
$storage[$level][$old] = $new;
unset($array[$old]);
} else {
if (isset($array[$old])) {
static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
} else if (isset($array[$storage[$level][$old]])) {
static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
}
}
}
}
}
/**
* Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
* #param type $map
* #param type $array
*/
public static function renameArrayKeys($map = [], &$array = [])
{
$storage = [];
static::__renameArrayKeysRecursive($map, $array, 0, $storage);
unset($storage);
}
}
Use:
DataHelper::renameArrayKeys([
'a' => 'b',
'abc.' => [
'abcd' => 'dcba'
]
], $yourArray);
It is from duplicated question
$json = '[
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';
$array = json_decode($json, true);
$out = array_map(function ($product) {
return array_merge([
'price' => $product['product_price'],
'quantity' => $product['product_quantity'],
], array_flip(array_filter(array_flip($product), function ($value) {
return $value != 'product_price' && $value != 'product_quantity';
})));
}, $array);
var_dump($out);
https://repl.it/#Piterden/Replace-keys-in-array
This is how I rename keys, especially with data that has been uploaded in a spreadsheet:
function changeKeys($array, $new_keys) {
$newArray = [];
foreach($array as $row) {
$oldKeys = array_keys($row);
$indexedRow = [];
foreach($new_keys as $index => $newKey)
$indexedRow[$newKey] = isset($oldKeys[$index]) ? $row[$oldKeys[$index]] : '';
$newArray[] = $indexedRow;
}
return $newArray;
}
Based on the great solution provided by Alex, I created a little more flexible solution based on a scenario I was dealing with. So now you can use the same function for multiple arrays with different numbers of nested key pairs, you just need to pass in an array of key names to use as replacements.
$data_arr = [
0 => ['46894', 'SS'],
1 => ['46855', 'AZ'],
];
function renameKeys(&$data_arr, $columnNames) {
// change key names to be easier to work with.
$data_arr = array_map(function($tag) use( $columnNames) {
$tempArray = [];
$foreachindex = 0;
foreach ($tag as $key => $item) {
$tempArray[$columnNames[$foreachindex]] = $item;
$foreachindex++;
}
return $tempArray;
}, $data_arr);
}
renameKeys($data_arr, ["STRATEGY_ID","DATA_SOURCE"]);
this work perfectly for me
$some_options = array();;
if( !empty( $some_options ) ) {
foreach( $some_options as $theme_options_key => $theme_options_value ) {
if (strpos( $theme_options_key,'abc') !== false) { //first we check if the value contain
$theme_options_new_key = str_replace( 'abc', 'xyz', $theme_options_key ); //if yes, we simply replace
unset( $some_options[$theme_options_key] );
$some_options[$theme_options_new_key] = $theme_options_value;
}
}
}
return $some_options;
I have a string, I need to know at what index is that string exist in the array. My array is as follows:
array(3)
{
[0]=>object(stdClass)#47170 (3)
{
["countries"]=>string(2) "HK"
["last_seen_date"]=>string(10) "2016-09-17"
["ad_uid"]=>string(14) "157d5908a1ca83"
}
[1]=>object(stdClass)#47171 (3)
{
["countries"]=>string(2) "HK"
["last_seen_date"]=>string(10) "2016-09-27"
["ad_uid"]=>string(14) "157d7978513bc3"
}
[2]=>object(stdClass)#47230 (3)
{
["countries"]=>string(2) "HK"
["last_seen_date"]=>string(10) "2016-09-27"
["ad_uid"]=>string(14) "157ea7239824e9"
}
}
The last seen date is:2016-09-27.
I would like to know at what index does 2016-09-27 exist in the array. So I know what is ad_uid related to that date. I have a method which does this.
public function getAd_uid($last_seen_date,$values){
$key = array_keys($values,$last_seen_date);
print_r($key);
}
The result gets an empty array. I have tried array_serach() has same empty results. Any other alternative solutions to achieve results?
To find all $ad_uids last_seen at particular date you can use array_filter which will return you all elements you are looking for. If you need ad_uids only, you can apply array_map to that array as following:
<?php
// $array is the array in question.
$filtered = array_filter($array, function($item) {
return $item->last_seen_date == "2016-09-27";
});
$ad_uids = array_map(function($item){return $item->ad_uid;}, $filtered);
Example
As each each entry of your array is an object and you know the attributs' names of theses objects (I assume they never change), I would do it like this :
/**
* #param string $last_seen_date
* #param array $values
* #return mixed null|int
*/
function getAdUid($last_seen_date, array $values) {
// Just in case no entry match
$matching_index = null;
// Loop through each entry: $entry is an object
foreach($values as $index => $entry) {
if($entry->last_seen_date == $last_seen_date) {
$matching_index = $index;
break; // end loop: we found that we are looking for
}
}
return $matching_index;
}
to do that just loop your array
foreach($values as $key => $row) {
// do something
}
then check if $last_seen_date is equal to the loop index last_seen_date $row->last_seen_date
if ($row->last_seen_date == $last_seen_date) {
return $key;
}
if it is just return it
return $key;
so your php code would be like this
$arr = array(
0 =>
(object)array(
"countries" => "HK",
"last_seen_date" => "2016-09-17",
"ad_uid"=> "157d5908a1ca83"
),
1 =>
(object)array(
"countries" => "HK",
"last_seen_date" => "2016-09-20",
"ad_uid" => "157d7978513bc3"
),
2 =>
(object)array(
"countries" => "HK",
"last_seen_date" => "2016-09-26",
"ad_uid" => "157ea7239824e9"
)
);
function getAd_uid($last_seen_date, $values){
foreach($values as $key => $row) {
if ($row->last_seen_date == $last_seen_date) {
return $key;
}
}
}
echo '2016-09-17 is on index => '.getAd_uid('2016-09-17', $arr).'<br>';
echo '2016-09-20 is on index => '.getAd_uid('2016-09-20', $arr).'<br>';
echo '2016-09-26 is on index => '.getAd_uid('2016-09-26', $arr).'<br>';
RESULT
Working Demo
On my left hand I've got this "key" :
localisation.adresse.commune.id
and many other values like this one, wich are dynamics (i can't use them literraly in my code as i don't know what they will be).
On the other hand i have an array like this (comes fron a json decoded) :
Array
(
[localisation] => Array
(
[adresse] => Array
(
[adresse1] => Le Chatelard
[codePostal] => 42820
[etat] => France
[commune] => Array
(
[id] => 16418
)
)
)
)
I can't list all the "keys" i'm going to exploit, so I need to automatically get the value of $object['localisation']['adresse']['commune']['id'].
I've tried this but it does not work :
$test['localisation']['adresse']['commune']['id'] = 16418 ;
$var = '$test[\'localisation\'][\'adresse\'][\'commune\'][\'id\']' ;
echo $var ; // $test['localisation']['adresse']['commune']['id']
var_dump($$var) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
var_dump(${$var}) ; // NULL Notice: Undefined variable: $test['localisation']['adresse']['commune']['id']
I suppose it's looking for a simple variable of a complicated name, instead of looking at a multidimentional array, but i don't know how i can do it...
Thans for your help !
I see no other way except traversing the array and trying to find the keys in internal arrays, if there are any.
I came up with two variants: recursive and iterative. They will also handle the case when the "depth" of the key and array differ, e.g. if your $key will contain more elements than the depth of the array, then the NULL will be returned, if less - then whatever is under the last key will be returned.
Recursive variant
$a = [
'localisation' => [
'adresse' => [
'adresse1' => 'Le Chatelard',
'codePostal' => 42820,
'etat' => 'France',
'commune' => [
'id' => 16418,
],
],
],
];
$key = 'localisation.adresse.commune.id';
function getValueByKeyRecursively($a, $key)
{
$keyList = explode('.', $key);
$currentKey = array_shift($keyList);
// Found the value
if (empty($currentKey)) {
return $a;
}
// No more depth to traverse or no such key
if (!is_array($a) || !array_key_exists($currentKey, $a)) {
return null;
}
return getValueByKeyRecursively($a[$currentKey], implode('.', $keyList));
}
var_dump(getValueByKeyRecursively($a, $key)); // outputs: int(16418)
Iterative variant
function getValueByKey(array $a, $key)
{
$keyList = explode('.', $key);
$returnValue = $a;
do {
$currentKey = array_shift($keyList);
// Found the value
if ($currentKey === null) {
break;
}
// No more depth to traverse or no such key
if (!is_array($returnValue) || !array_key_exists($currentKey, $returnValue)) {
return null;
}
$returnValue = $returnValue[$currentKey];
} while (true);
return $returnValue;
}
var_dump(getValueByKey($a, $key)); // outputs: int(16418)
try this :
$str = '{
"localisation" : {
"adresse" : {
"adresse1" : "Le Chatelard",
"codePostal" : "42820",
"etat" : "France",
"commune" : {
"id" : 16418
}
}
}
}
';
$data = json_decode($str, true);
$var = $data['localisation']['adresse']['commune']['id'] ;
echo $var ;
print_r($data);
Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
foreach($parentObj AS $key=>$element){
if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
echo "Gottcha! The index is - ". $key;
}
}
$parentObj is obviously your root array - the one that holds all the others.
We use the foreach loop to iterate over each item and then test it's id property against what ever value you desire. Once we have that - the $key that we are on is the index you are looking for.
use array_search:
$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;
$arr = array($a, $b);
$index = array_search($b, $arr);
echo $index;
// prints out 1
try this
foreach($array AS $key=>$object){
if($object['id'] == 4){
$key_in_array = $key;
}
}
// chop it from the original array
array_slice($array, $key_in_array, 1);
Another way to achieve the result is to use array_filter.
$array = array(
(object)array('id' => 5),
(object)array('id' => 4),
(object)array('id' => 3)
);
$array = array_filter($array, function($item) {
return $item->id != 4;
});
print_r($array);
Here's my solution. Given, it is a bit hackish, but it will get the job done.
search(array $items, mixed $id[, &$key]);
Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.
function search($items, $id, &$key = null) {
foreach( $items as $item ) {
if( $item->id == $id ) {
$key = key($item);
return $item;
break;
}
}
return null;
}
Usage
$item = search($items, 4, $key);
unset($items[$key]);
Note: This could be modified to allow a custom key and return multiple items that share the same value.
I've created an example so you can see it in action.
A funny alternative
$getIdUnset = function($id) use ($myArray)
{
foreach($myArray as $key => $obj) {
if ($obj->id == $id) {
return $key;
}
}
return false;
};
if ($unset = $getIdUnset(4)) {
unset($myArray[$unset]);
}
Currently php does not have any supported function for this yet.
So refer to Java's Vector, or jQuery's $.inArray(), it would simply be:
public function indexOf($object, array $elementData) {
$elementCount = count($elementData);
for ($i = 0 ; $i < $elementCount ; $i++){
if ($object == $elementData[$i]) {
return $i;
}
}
return -1;
}
You can save this function as a core function for later.
In my case, this my array as $array
I was confused about this problem of my project, but some answer here helped me.
array(3) {
[0]=> float(-0.12459619130796)
[1]=> float(-0.64018439966448)
[2]=> float(0)
}
Then use if condition to stop looping
foreach($array as $key => $val){
if($key == 0){ //the key is 0
echo $key; //find the key
echo $val; //get the value
}
}
I know, after so many years this could be a useless answer, but why not?
This is my personal implementation of a possible index_of using the same code as other answers but let the programmer to choose when and how the check will be done, supporting also complex checks.
if (!function_exists('index_of'))
{
/**
* #param iterable $haystack
* #param callable $callback
* #param mixed|null &$item
* #return false|int|string
*/
function index_of($haystack, $callback, &$item = null)
{
foreach($haystack as $_key => $_item) {
if ($callback($_item, $_key) === true) {
$item = $_item;
return $_key;
}
}
return false;
}
}
foreach( $arr as $k=>&$a) {
if( $a['id'] == 4 )
unset($arr[$k]);
}
I need to merge some arrays in some different way and I use array_merge_recursive.
However there is something that I need to change and I don't know how.
Here is quote from php.net
If, however, the arrays have the same numeric key, the later value
will not overwrite the original value, but will be appended.
I want this value, NOT to be appended, I want not to append exact values in the new array.Hope you've understood this.
Example:
$array = array(
'some' => array(
'other' => 'key',
),
);
$array2 = array();
$array2['some']['other'] = 'key2';
If I use array_merge_recursive It will result this:
Array (
[some] => Array
(
[other] => Array
(
[0] => key
[1] => key2
)
) )
I want if it matches the same result, not to append it.Yes I know, you would say, then use array_merge, but it doesn't work well, too.
If I use this:
$array = array(
'some' => array(
'other' => 'key',
),
);
$array2 = array();
$array2['some']['other2'] = 'key2';
print_r(array_merge($array, $array2));
It will remove $array[some][other] from the list and leave only $array[some][other2].I don't know which is better, since no one makes it better.
For PHP >= 5.3 just use array_replace_recursive
try this
<?php
function mymerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
foreach($b as $child=>$value){
if(isset($a[$child])){
if(is_array($a[$child]) && is_array($value)){ //merge if they are both arrays
mymerge($a[$child],$value);
}
//else ignore, you can add your own logic, i.e when 1 of them is array
}
else
$a[$child]=$value; //add if not exists
}
//return $a;
}
An other alternative, the array_merge_deep from drupal:
function array_merge_deep($arrays) {
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
// Recurse when both values are arrays.
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = array_merge_deep(array($result[$key], $value));
}
// Otherwise, use the latter value, overriding any previous value.
else {
$result[$key] = $value;
}
}
}
return $result;
}
I wrote my merge class for it:
<?php
class ArrayMerge
{
/**
* #param array $a
* #param array $b
*
* #return array
*/
public function merge ( $a, $b ) {
foreach ( $b as $k => $v ) {
if ( is_array( $v ) ) {
if ( isset( $a[ $k ] ) ) {
if ( $this->isDeep( $v ) ) {
$a[ $k ] = $this->merge( $a[ $k ], $v );
} else {
$a[ $k ] = array_merge( $a[ $k ], $v );
}
} else {
$a[ $k ] = $v;
}
} else {
$a[ $k ] = $v;
}
}
return $a;
}
/**
* #param array $array
*
* #return bool
*/
private function isDeep ( $array ) {
foreach ( $array as $elm ) {
if ( is_array( $elm ) ) {
return TRUE;
}
}
return FALSE;
}
}
I started from RiaD's version and added object handling. Need testing and feedback
function recursiveMerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
if(is_array($b) || is_object($b)){
foreach($b as $child=>$value){
if(is_array($a)){
if(isset($a[$child]))
recursiveMerge($a[$child],$value);
else
$a[$child]=$value;
}
elseif(is_object($a)){
if(isset($a->{$child}))
recursiveMerge($a->{$child},$value);
else
$a->{$child}=$value;
}
}
}
else
$a=$b;
}