Can I merge two equally sized arrays into one array with sub-arrays of merged values?
I'm not sure why you have Hash
involved. Array#zip
is the method you need.
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
a.zip(b) # => [["a1", "b1"], ["a2", "b2"], ["a3", "b3"]]
Can I merge two equally sized arrays into one array with sub-arrays of merged values?
I'm not sure why you have Hash
involved. Array#zip
is the method you need.
a = ["a1", "a2", "a3"]
b = ["b1", "b2", "b3"]
a.zip(b) # => [["a1", "b1"], ["a2", "b2"], ["a3", "b3"]]
How to add merge subarrays of two multi-dimensional arrays
Sadly, it takes a fair amount of iterating/preparation to get your two arrays ready for use with array_merge_recursive()
. I'll admit, I'm not proud of the convolution in my method. The major factor in all this is that array_merge_recursive()
only "plays nicely" with non-numeric indexes, so I had to replace your numerically indexed keys with relative id values within the arrays. I'll do my best to explain my steps, but again, it's not pretty... (Demo)
Step #1: Prepare $stock
array:
foreach($stock as $subarray){
$new_stock["#{$subarray['productid']}"]=$subarray; // replace outer key
$new_variants=[]; // declare a fresh array
foreach($subarray['variants'] as $varsub){
$new_variants["#{$varsub['variantId']}"]['isInStock']=$varsub['isInStock']; // one element only
// omitting variantId element this time as the next array will offer it.
}
$new_stock["#{$subarray['productid']}"]['variants']=$new_variants;
}
Step #2: Prepare $data
array & merge:
foreach($data as $subarray){
$new_data["#{$subarray['productid']}"]=$subarray; // replace outer key
$new_variants=[]; // declare a fresh array
foreach($subarray['variants'] as $varsub){
$new_variants["#{$varsub['variantId']}"]=$varsub; // both elements from variants
}
$new_data["#{$subarray['productid']}"]['variants']=array_values(array_merge_recursive($new_variants,$new_stock["#{$subarray['productid']}"]['variants']));
// new variants subarray has been merged, re-indexed, and written to $new_data
}
Step #3: re-index outer array keys, and display:
$result=array_values($new_data);
var_export($result);
The bulk of the array preparations is to generate unique id's for the outer and inner arrays (in both $stock
& $data
). This permits the array_merge to isolate the related productid
s and recursively merge the variant
elements.
If these two arrays are being generated from a database, then my high recommendation is to utilize available database functionality to merge this data instead of php.
For a simple example of how array_merge_recursive()
works here's a small demo. Experiment with the keys in either of the arrays. If you so-much-as remove the #
from the numeric string, array_merge_recursive()
will assume that it's dealing with numeric indexes and mince things up. My technique to preserve your id's as strings was to prepend the #
, but it could have been done by adding any of a range of non-digit characters to the key value.
Arrays, subarrays and merging subarrays within an array
After some clarifications, I believe this is what you want:
object.append([object_location])
First of all, I think you're a little confused between lists and arrays. They're similar, but a little different. In python, arrays are called lists. In numpy, they are arrays. What you're currently doing is simply inserting a bunch of 1D numpy arrays into a list, which looks somewhat like this:
[array([3, 3]), array([2, 3]), array([0, 1])]
Now, if you were to try to append something to, say element 0, you would get
AttributeError: 'numpy.ndarray' object has no attribute 'append'
Because numpy arrays cannot be appended to the way lists can (they're fixed in size).
What you'd want, instead, is to have each array be put into another list, like this:
[[array([3, 3])], [array([2, 3])], [array([0, 1])]]
(Note the extra [...]
around each array.
Now, when you try appending to, say, the 0th inner list, you'll get something like this:
[[array([3, 3]), array([4, 1])], [array([2, 3])], [array([0, 1])]]
Notice you've successfully appended another 1D array to the first one.
If all your inner lists have the same dimensions, you can then use np.asarray(your_list)
to convert it to a 3D array (rather than a list of list of arrays):
[[[3 3]
[4 1]]
[[2 3]
[3 4]]
[[0 1]
[2 0]]]
How to merge two arrays based on their index php?
A simple foreach loop using the index and value parameters will do it in no time
Example
$a1 = ['name-file_icon_001_00.png-',
'name-file_icon_002_00.png-',
'name-file_icon_003_00.png-'
];
$a2 = ['rel1','rel2','rel3'];
foreach ($a1 as $i => $v){
$new[] = $v . $a2[$i];
}
print_r($new);
RESULT
Array
(
[0] => name-file_icon_001_00.png-rel1
[1] => name-file_icon_002_00.png-rel2
[2] => name-file_icon_003_00.png-rel3
)
Combine elements from two arrays into subarrays in a third array
Here is what I came up with to solve your issue. Also, try using alert() instead of console.log() to see the true results. console.log() sometimes does not display everything, and so you need to expand some of what it stores:
var arr1 = ["Quote1", "Quote2", "Quote3"];
var arr2 = ["Author1", "Author2", "Author3"];
// the output I need to achieve:
//[ ["Quote1", "Author1"], ["Quote2", "Author2"], ["Quote3", "Author3"] ];
var newArr = [[],[],[]];
for(var i = 0; i < newArr.length; i++){
newArr[i].push(arr1[i]);
newArr[i].push(arr2[i]);
}
alert(newArr);
PHP merge two arrays on the same key AND value
Try out this code, It might help you, it's short and without traversing loops:
usort($array2,function($a,$b){
return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
});
$array3 = array_replace_recursive($array1, $array2);
$result = array_uintersect($array3,$array1,function($a,$b){
return strnatcmp($a['ur_user_id'],$b['ur_user_id']);
});
print_r($result);
Output
Array
(
[0] => Array
(
[ur_user_id] => 1
[ur_fname] => PerA
[ur_lname] => SonA
[ur_code] => AA
[ur_user_role] => testA
)
[1] => Array
(
[ur_user_id] => 2
[ur_fname] => PerB
[ur_lname] => SonB
[ur_code] => BB
[ur_user_role] => testB
)
[2] => Array
(
[ur_user_id] => 3
[ur_fname] => PerC
[ur_lname] => SonC
[ur_code] => CC
[ur_user_role] => testC
)
)
And Here is Demo
Related Topics
How to Verify Pacts Against an API That Requires an Auth Token
Implementing Dry-Run in Ruby Script
Bind and Destructure Block Arguments
Local Server Error After Upgrading Ruby from 1.8.7 to 1.9.2 (With Rails 3.1.1)
Understanding Usage of Symbols in Routes.Rb Files
How to Require Activerecord in Irb
How to Convert a Large Gem to Standalone Rails App
How to Fix My Cucumber Expectation Error When Polling
How to Schedule a Function to Execute at a Future Time
Use Variable in Parameter Ruby on Rails
How to Collect Real-Time Tweets
Rails: Logging the Entire Stack Trace of an Exception
Gracefully Shutting Down Sidekiq Processes