How to Add an Array to Another Array in Ruby and Not End Up With a Multi-Dimensional Result

Update multidimensional array values with another multidimensional array without using any loop

The arrays $newArray and $oldArray are required with the id as the key. array_column does that. Then array_replace_recursive() can be used.

$old = array_column($oldArray,null,'id');
$new = array_column($newArray,null,'id');
$updatedArray = array_values(array_replace_recursive($old, $new));

Without array_values() the result array has the 'id' as key. array_replace() is also sufficient for this case.

try self: 3v4l.org

PHP divide multidimensional array into two part with comparing another array

This data has been changed in such a way that an element with key 41 from new matches that from old.

$priceNew = [
42 => [ 110, 0.00 ],
41 => [ 80, 70.00 ],
43 => [ 70, 60 ],
40 => [ 90, 80 ],
];

$priceOld = [
42 => [
'sales_price' => 100.00,
'our_price' => 0.00
],
41 => [
'sales_price' => 80.00,
'our_price' => 70.00
],
];

You just have to compare the keys. This can be done with the internal PHP functions array_intersect_key and array_diff_key. The update array is still filtered to meet special conditions.

$updateArr = array_intersect_key($priceNew, $priceOld);

$filter = function($v,$k) use($priceOld){
return array_values($priceOld[$k]) != $v;
};

$updateArr = array_filter($updateArr, $filter, ARRAY_FILTER_USE_BOTH );
$otherArr = array_diff_key($priceNew,$updateArr); //added or remained

How to compare each first index of multidimensional array and to push into another array if they are the same

It sounds like you want to split the data into separate arrays, with each array containing only the entries relating to a single SKU.

As you mentioned in the comments that the top-level array can be indexed associatively rather than numerically, this makes it quite trivial to allocate items to each sub-array by reading the SKU from the item.

e.g.

$output = array();

foreach ($input as $item)
{
$sku = $item["SKU"];
$output[$sku][] = $item;
}

Live demo: http://sandbox.onlinephpfunctions.com/code/770b4fcc096449ee6c0a9fd39174f5b6bcd4106a

How to join two nested subarrays (inside multidimensional array) elements in Ruby?

Use each_slice

 p array.each_slice(2).map {|v| v.flatten}

add new items to multidimensional Ruby hash in loop

This seems pretty straightforward. No need to loop over all of the key/value pairs looking for :customers when we can access it directly.

if bannerhash.has_key?(:customers)
bannerhash[:customers].each { |h|
h[:image][:newitem] = "https://cdn.doma.com/s/files/1/0611/2064/3323/files/yellow-pillow-bedside- table_3300x.jpg?v=1637223489"
}
else
puts "banners not found"
end


Related Topics



Leave a reply



Submit