Array merge on multidimensional array
$out = array();
foreach ($arr1 as $key => $value){
$out[] = (object)array_merge((array)$arr2[$key], (array)$value);
}
print_r($out)
Push elements from one array into rows of another array (one element per row)
$i=0;
$NewArray = array();
foreach($OriginalArray as $value) {
$NewArray[] = array_merge($value,array($_FILES['Upload']['name'][$i]));
$i++;
}
the [] will append it to the array instead of overwriting.
Merge multidimensional Array PHP without changing the key
You can use Array Operators +
to do that. You can check my below demo:
<?php
$array = [
array(
"image" => "logo.jpg",
"name" => "data",
"server"=> "Mirani Rahmawati",
"6" => "5"
),
array(
"image"=> "logo.jpg",
"name" => "data",
"server"=> "Mirani Rahmawati",
"5" => "150"
)
];
$result = [];
foreach ($array as $item) {
$result = $result + $item;
}
print_r($result);
exit;
?>
The result will be:
Array
(
[image] => logo.jpg
[name] => data
[server] => Mirani Rahmawati
[6] => 5
[5] => 150
)
You can find out more at https://www.php.net/manual/en/language.operators.array.php
PHP - Multidimensional array merge to one array
array-map with combination of array-merge should do the trick:
$c = array_map('array_merge', $a, $b);
Live example: 3v4l
Merge multidimensional array in php with duplicate values
Another way in which you can get the stockitems
with same id
in a unique array
.
<?php
$input = Array ( Array
('orderId' => '1544100294',
'total' => 215.28,
'receivedate' => '0000-00-00',
'stockitemname' => 'The Gu red shirt XML tag t-shirt (White) XXS',
'customerid' => 10 ),
Array
( 'orderId' => '1544119651',
'total' => 37.38,
'receivedate' => '0000-00-00',
'stockitemname' => 'USB rocket launcher (Gray)',
'customerid' => 10 ),
Array
( 'orderId' => '1544100294',
'total' => 1614.60,
'receivedate' => '0000-00-00',
'stockitemname' => 'Large sized bubblewrap roll 50m',
'customerid' => 10 ) );
// New array using orderId as the key
$output = array();
foreach ($input as $values) {
// Define your key
$key = $values['orderId'];
// Assign to the new array using all of the actual values
$output[$key][] = $values;
}
// Get all values inside the array, but without orderId in the keys:
$output = array_values($output);
// Print the new array
print_r($output);
?>
Here you can see it working !
Merge multiple multidimensional arrays and group by id column
First, why is your code slow? Assuming you have 1000 elements, your code is doing 1000*(1000+1000) = 2 millions iterations. That's why.
How to make it faster? Use assoc arrays instead of normal arrays, i.e. use id_produto
as the key, so you can have direct access to the right elements instead of having to do a loop inside a loop.
To do that, first convert array2 and array3. Example with array2:
$new_array2 = array();
foreach ( $array2 as $row ) {
$new_array2[$row['id_produto']] = $row;
}
$array2 = $new_array2;
Then merge:
foreach ( $array1 as & $row ) {
$row['pageviews'] = $array2[$row['id_produto']['pageviews']];
$row['pedidos'] = $array3[$row['id_produto']['pedidos']];
$row['valor'] = $array3[$row['id_produto']['valor']];
}
Total : 3000 iterations only.
multidimensional array merge into one array if key is same without using nested loop
You can use the following code to recursively iterate of all your structure and extract only data you need (by key). I assume $data has your original data structure and within $result you will get array of area:
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data), RecursiveIteratorIterator::SELF_FIRST);
$result = [];
foreach ($it as $k => $v) {
if ($k === 'area') {
$result = array_merge($result, $v);
}
}
Merge a multidimensional array and retain non-empty values when possible
I'll demonstrate a few alternative techniques with different benefits that rely on the fact that all columns are represented in all rows. I don't see any benefit to generating a 2-dimensional output array, so all of my snippets will produce the same flat, associative array.
No matter which style you prefer, at least two loops will be required -- one to iterate rows and one to iterate the elements in each row.
Standard nested loops: (Demo)
$result = array_shift($array); // remove the first row and push it into the result array
foreach ($array as $row) {
foreach ($row as $key => $value) {
if ($value !== '') {
$result[$key] = $value; // only overwrite where a non-empty value exists
}
}
}
var_export($result);
Semi-function-based iteration: (Demo)
$result = array_shift($array); // remove the first row and push it into the result array
foreach ($array as $row) {
$result = array_merge($result, array_filter($row, 'strlen')); // merge only non-empty elements into the result
}
var_export($result);
*Note, just in case your actual project has more than your posted four fields AND one of those fields may hold a zero value that you don't want to filter out, use strlen
as a parameter in array_filter()
. Otherwise, array_filter()
will greedily kill off an null, false, zeroish, and zero-width values.
Fully-function-based with array_reduce()
: (Demo)
var_export(
array_reduce(
$array,
function($carry, $row) {
$carry = array_merge($carry, array_filter($row, 'strlen'));
return $carry;
},
array_shift($array)
)
);
Fully-function-based with array_merge_recursive()
: (Demo)
var_export(
array_map('max', array_merge_recursive(...$array))
);
This one is most brief, but is - admittedly - taking advantage of the fact that max()
will return the desired strings from each column. This approach may not be suitable for all scenarios as a general-use technique.
Effectively, this is unpacking $array
into $row[0], $row[1], $row[2]
(using ...
) then transposing the data into subarrays of column data (maintaining the first level keys using array_merge_recursive()
), then reducing each subarray to its "highest" value (using max()
on each subarray).
Sahil's answer is not very robust/trustworthy because it manually corrects the missing uri
key's value after the process is complete. This adjustment is made purely because the missing value is "known" to the programmer. Programmatically speaking, this is lazy, prone to failure, and should not be used by SO readers.
Related Topics
Creating a Very Simple 1 Username/Password Login in PHP
Supplied Argument Is Not a Valid MySQL Result Resource
Isset() Function Is Returning True Even When Item Is Not Set
Concatenate PHP Function Output to a String Like Variables
How to Retrieve All Variables from a Twig Template
PHP Checkbox Set to Check Based on Database Value
PHP Allocate Color Without Image Resource
How to Minify Js in PHP Easily...Or Something Else
Block Specific Ip Block from My Website in PHP
How to Enable Shell_Exec and Exec on PHP
Convert a JSON into a Utf-8 String
Is This a PHP Date() Bug, or Is There Something Wrong with My Code
Place PHP Results Inside HTML Page
Combine 2-3 Transparent Png Images on Top of Each Other with PHP
Using Preg_Split with Multiple Spaces