combine two (or more..) multi-dimensional arrays in php -
I have a query that I run multiple times with multiple parameters I return the results to jQuery in an XML I am using the parser.
I can not find any way to combine the results of 'node' without overwriting the entry first.
Simplified code sample:
$ temp1 = returnArray (0); $ Temp2 = returnback (1); $ Data = array_merge ($ temp1, $ temp2); Print_r ($ data); Function returns ($ switch) {if ($ switch == 0) {$ data ['data'] ['first'] = "something"; } And {$ data ['data'] ['second'] = "something else"; } Return $ data; }
Result Aare ([data] => array ([seconds] => some ELSE)) Overwrite $
- $ temp2 $ temp1 Used to be . I consider it as the default behavior of array_merge (), which is confusing to me
I also have the $ data = $ temp1 + $ temp2;
or tried something like this.
$ data = return again (0); $ Data + = return (1);
print aa ([data] => array ([first] = & gt; some))
or .. .
$ data = return again (0); $ Data Return = array (1); Print_r ($ data);
Print ArrayArray
I ended hacking it together:
$ data [ Data '] = return again (0); $ Data ['data'] = return again (1); Function Returner ($ Switch) {if ($ switch == 0) come back ('first' = & gt; 'some'); Return Array ('second' = & gt; 'some more'); }
That which I am not happy with all ... though this work is done in this case, it will not be all that apply in the future when there is a more complex situation .
Is there a better way of combating two companionship, multidimensional arrays and without overwriting them?
EDIT:
I want to be able to handle the 2+ array with a re-usable, extensible and 2+ dimensions.
PHP actually provides a function that is used properly in this type of scenario. From:
array_merge_recursive ()
One or more arrays merge into elements together so that the value of one is added to the end Go gives the array as a result of the previous one.If input arrays have the same string key, then the values of these moves are merged together in the array, and it is done recursively, so if one of the values is an array , The function will also merge it into a related entry in another entry. If, however, arrays have the same numeric key, the subsequent values will not overwrite the original value, but they will be added.
Example:
& lt ;? Php $ ar1 = array ("color" => array ("favorites" =>, "red"), 5); $ AR2 = array (10, "color" => array ("favorites" =>, "green", "blue")); $ Result = array_merge_recursive ($ AR1, $ AR2); Print_r ($ result); ? & Gt; Array ([color] => array ([favorite] = & gt; array ([0] Output: ] = & Gt; Red [1] = & gt; Green) [0] = & gt; Blue) [0] => 5 [1] => 10)
Comments
Post a Comment