PHP concatenates two associative arrays
$ array 1: -
Array
(
[Test Stock] => Array
(
[intStockCount] => 10
)
[CARTON 50 X 50 X 50] => Array
(
[intStockCount] => 10
)
)
$ array2: -
Array
(
[Test Stock] => Array
(
[intInvoiceCount] => 20
)
[CARTON 50 X 50 X 50] => Array
(
[intInvoiceCount] => 30
)
)
I need a new array that concatenates everything together without using a loop
Array
(
[Test Stock] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 20
)
[CARTON 50 X 50 X 50] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 30
)
)
source to share
You can use array_merge_recursive
to complete the task.
array_merge_recursive () concatenates the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, the values of those keys are concatenated into an array, and this is done recursively, so if one of the values is the array itself, the function will concatenate it with the corresponding entry in the other array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be added.
Just do:
<?php
$array1 = array(
"Test Stock" => array(
"intStockCount" => 10
),
"CARTON 50 X 50 X 50" => array(
"intStockCount" => 10
)
);
$array2 = array(
"Test Stock" => array(
"intInvoiceCount" => 20
),
"CARTON 50 X 50 X 50" => array(
"intInvoiceCount" => 30
)
);
$final = array_merge_recursive($array1,$array2);
echo '<pre>';
print_r($final);
echo '</pre>';
/* OUTPUT
Array
(
[Test Stock] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 20
)
[CARTON 50 X 50 X 50] => Array
(
[intStockCount] => 10
[intInvoiceCount] => 30
)
)
*/
It's important to note that you are using the same line key
in both arrays
. Since the docs docs are in the format
... the values of these keys are combined into an array
source to share
$array1 = array(
'Test Stock' => array(
'intStockCount' => 10,
),
'CARTON 50 X 50 X 50' => array(
'intStockCount' => 10
)
);
$array2 = array(
'Test Stock' => array(
'intStockCount' => 10,
),
'CARTON 50 X 50 X 50' => array(
'intStockCount' => 10
)
);
$result = array_merge_recursive($array1, $array1);
var_dump($result);
You have to change the structure of the array.
For normal array merging:
$result = array_merge($array1, $array2);
source to share