How to merge multiple two dimensional array based on first dimension key? - php

My problem statement is like follows:
Suppose I have 2 two dimensional array. The arrays are:
$array1 = Array
(
[8] => Array
(
[branch_code] => DG-52484
[total_desg] => 11
)
);
$array2 = Array
(
[8] => Array
(
[total_dak] => 0
[total_dak_decision] => 0
)
);
After combining the two array my required out put will be:
Array
(
[8] => Array
(
[branch_code] => DG-52484
[total_desg] => 11
[total_dak] => 0
[total_dak_decision] => 0
)
);
Is there any php function for this type of task. Please note that i am not interested to use foreach or while in my situation.
Thanks in advance.

It will work with array_replace_recursive:
$array1 = Array(
8 => Array(
'branch_code' => 'DG-52484',
'total_desg' => '11',
)
);
$array2 = Array
(
8 => Array(
'total_dak' => 0,
'total_dak_decision' => 0,
)
);
var_dump(array_replace_recursive($array1, $array2));
Output
array (size=1)
8 =>
array (size=4)
'branch_code' => string 'DG-52484' (length=8)
'total_desg' => string '11' (length=2)
'total_dak' => int 0
'total_dak_decision' => int 0

try to use
$array = array(
8 => array_merge($array1[8],$array2[8]);
);

You can use array_merge
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Output
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
For more info http://php.net/manual/tr/function.array-merge.php

Related

Consolidate differently structured arrays into one without rearranging keys or values

I have a page that has 4 widgets each getting data from the database. Each widgets gets data in different formats since i have a table widget, a statistics widget and a widget with just one value.
Supposing i have the results of queries returning data say in this format
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
how can i pass the arrays as json encoded as one but retains their array structure on the client side for easier and faster creating on widget views?.
I have looked at array_merge and according to the docs, that's not what i am looking for.
how can i pass the arrays as json encoded as one but retains their array structure on the client side for easier and faster creating on widget views?.
You might arrange each array to be json encoded together like so:
$bundle = json_encode([$arr1, $arr2, $test1, $array1, $array2]);
Result:
[[1,3,5],[2,4,6],{"11":"11","22":"22","33":"33","44":"44"},{"0":"zero_a","2":"two_a","3":"three_a"},{"1":"one_b","3":"three_b","4":"four_b"}]
If I understood your issue correctly, you can assign your arrays to a multidimensional array.
Based in your example:
$dataArray = [];
$arr1 = array(1, 3, 5);
$arr2 = array(2, 4, 6);
$dataArray['data_type_one'][] = $arr1;
$dataArray['data_type_one'][] = $arr2;
$test1 = array(
'11' => '11',
'22' => '22',
'33' => '33',
'44' => '44'
);
$dataArray['data_type_two'] = $test;
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$dataArray['data_type_three'][] = $array1;
$dataArray['data_type_three'][] = $array2;
You will end up with this array structure:
Array
(
[data_type_one] => Array
(
[0] => Array
(
[0] => 1
[1] => 3
[2] => 5
)
[1] => Array
(
[0] => 2
[1] => 4
[2] => 6
)
)
[data_type_two] => Array
(
[11] => 11
[22] => 22
[33] => 33
[44] => 44
)
[data_type_three] => Array
(
[0] => Array
(
[0] => zero_a
[2] => two_a
[3] => three_a
)
[1] => Array
(
[1] => one_b
[3] => three_b
[4] => four_b
)
)
)
Then, in your views, you can do whatever you need:
foreach ($arrayData['data_type_one'] as $someData) {
echo $someData[0] . ' ';
//will print 1 2
}
echo $dataArray['data_type_two']['11'];
//will print 11

How to push an array in a multidimensional array into a specific subarray in another multidimensional array

I have two arrays:
$array1 = array(299945 => [13654 => [9917 => [0 => '0', 9 => '9', 33 => '33']]]);
$array2 = array(13654 => [9940 => [0 => '0']]);
Each of these are created from different DBQueries which create these results.
I know want to take the '9940' key from $array2 and push it into $array1 so that it will be another element in the 13654 array. Thus the final result would be:
$array1 = array(299945 =>[13654 => [9917 => [0 => '0', 9 => '9', 33 => '33'], 9940 => [0 => '0']]])
How can I do this?
There's a few ways of doing this, here's one that uses array_replace_recursive():
<?php
header('Content-type: text/plain');
$array1 = array(299945 => [13654 => [9917 => [0 => '0', 9 => '9', 33 => '33']]]);
$array2 = array(13654 => [9940 => [0 => '0']]);
$array3 = array_replace_recursive($array1, [key($array1) => $array2]);
print_r($array3);
Output:
Array
(
[299945] => Array
(
[13654] => Array
(
[9917] => Array
(
[0] => 0
[9] => 9
[33] => 33
)
[9940] => Array
(
[0] => 0
)
)
)
)
If you just want a union of two arrays, there is not much to it:
$array1 += $array2
You should probably think about more complex situation with duplicate keys and issues like that, so I usually find array_merge to be the better tool for adding two arrays together.

Merge two arrays, replacing values of same key

I have two arrays
First Array
(
[0] => Array
(
[352] => 1
[128] =>
[64] =>
[70] => 2
)
)
Second array is like this :
Array
(
[0] => Array
(
[128] => 1.5
)
)
I want to make final array like this.(i want to store the matching into the main array in this example it is 128 -> 1.5) how can i do it.?
Array
(
[0] => Array
(
[352] => 1
[128] => 1.5
[64] =>
[70] => 2
)
)
here is my array variables:
print_r($listskilssresult);
print_r($listskilssresultmatching);
You need to use array_replace_recursive
$listskilssresult = [
[
352 => 1,
128 => '',
64 => '',
70 => 2
]
];
$listskilssresultmatching = [
[
128 => 1.5
]
];
print_r(array_replace_recursive($listskilssresult, $listskilssresultmatching));
Prints :
Array
(
[0] => Array
(
[352] => 1
[128] => 1.5
[64] =>
[70] => 2
)
)
Know the difference between array_replace_recursive and array_merge_recursive here
This is specific to your question. If you want to make something more automated, you can create a function. But this will do what you want:
<?php
$array1 = [[352 => 1, 128 => null, 64 => null, 70 => 2]];
$array2 = [[128 => 1.5]];
$keys1 = array_keys($array1[0]);
$keys2 = array_keys($array2[0]);
foreach ($keys1 as $key => $value) {
if (in_array($value, $keys2)) {
$array1[0][$value] = $array2[0][$value];
unset($array2[0][$value]);
}
}
if (!empty($array2[0])) {
foreach ($array2[0] as $key => $value) {
$array1[0][$key] = $value;
unset($array2[0][$key]);
}
}
print_r($array1[0]);
?>
The last if statement will add key + value from the 2nd array to the first if no match was found for them (from the foreach statement). You can just delete that condition if you just want to add only matching keys.
For this solution, you have to use array_merge() built-in php function.
Syntax:
$finalArray = array_merge($array1, $array2);
print_r($finalArray)
Example:
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
Output:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
Reference : http://php.net/manual/en/function.array-merge.php
array_replace_recursive is the best solution!
$old_array = Array('my_index1' => Array('1' => 'A', '2' => 'B'), 'my_index2' => Array('1' => 'C', '2' => 'D'));
$new_array = Array('my_index2' => Array('2' => 'Z'));
$result = array_replace_recursive($old_array, $new_array);
//Result : Array('my_index1' => Array('1' => 'A', '2' => 'B'), 'my_index2' => Array('1' => 'C', '2' => 'Z'));
array_merge would do the job for you:
array_merge($listskilssresult,$listskilssresultmatching)

Filter multidimensional array by values of other array

Please help me to understand how can I succeed to filter a multidimensional with a help of other array value as keys for the first array.
$multidimensional = Array (
[0] => Array('var1' => val1),
[1] => Array('var2' => val2),
[2] => Array('var3' => val3),
[3] => Array('val4' => val4)
);
$filter = Array(1, 3);
The final result should be:
$multidimensional = Array (
[1] => Array('var2' => val2),
[3] => Array('val4' => val4)
);
It should be something similar as array_slice or other method how to easily perform such task. Thank you in advance!
You can use the array_intersect_key function:
$result = array_intersect_key($multidimensional, array_flip($filter));
To expand upon my comment with a small example
<?php
$arrayOne = [
1 => ['foo' => 'bar'],
2 => ['foo' => 'bar'],
3 => ['foo' => 'bar'],
4 => ['foo' => 'bar'],
];
$arrayTwo = [1 => [], 3 => []];
print_r(array_intersect_key($arrayOne, $arrayTwo));
see array_intersect_key on php.net
Another variation using array_diff_key and array_flip functions:
$multidimensional = array_diff_key($multidimensional, array_diff_key($multidimensional, array_flip($filter)));
print_r($multidimensional);
The output:
Array
(
[1] => Array
(
[var2] => val2
)
[3] => Array
(
[val4] => val4
)
)
http://php.net/manual/en/function.array-diff-key.php

Merge two multidimensional arrays and reindex all subarrays

I have two arrays, I want to merge these two arrays into single array. Please view the detail below:
First Array:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
)
[1] => Array
(
[a] => 3
[b] => 2
[c] => 1
)
)
Second Array:
Array
(
[0] => Array
(
[d] => 4
[e] => 5
[f] => 6
)
[1] => Array
(
[d] => 6
[e] => 5
[f] => 4
)
)
I want this result. Does somebody know how to do this?
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 3
[1] => 2
[2] => 1
)
[2] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[3] => Array
(
[0] => 6
[1] => 5
[2] => 4
)
)
Hope you have understand the question.
Thank you in advance.
Try array_merge:
$result = array_merge($array1, $array2);
FIXED (again)
function array_merge_to_indexed () {
$result = array();
foreach (func_get_args() as $arg) {
foreach ($arg as $innerArr) {
$result[] = array_values($innerArr);
}
}
return $result;
}
Accepts an unlimited number of input arrays, merges all sub arrays into one container as indexed arrays, and returns the result.
EDIT 03/2014: Improved readability and efficiency
more simple and modern way is:
$merged = $array1 + ['apple' => 10, 'orange' => 20] + ['cherry' => 12, 'grape' => 32];
new array syntax from php 5.4
If you want to return the exact result you specify in your question then something like this will work
function array_merge_no_keys() {
$result = array();
$arrays = func_get_args();
foreach( $arrays as $array ) {
if( is_array( $array ) ) {
foreach( $array as $subArray ) {
$result[] = array_values( $subArray );
}
}
}
return $result;
}
As a purely native function solution, merge the arrays, then reindex each subarray.
Code: (Demo)
$a = [
['a' => 1, 'b' => 2, 'c' => 3],
['a' => 3, 'b' => 2, 'c' => 1],
];
$b = [
['d' => 4, 'e' => 5, 'f' => 6],
['d' => 6, 'e' => 5, 'f' => 4],
];
var_export(
array_map('array_values' array_merge($a, $b))
);
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
2 => 3,
),
1 =>
array (
0 => 3,
1 => 2,
2 => 1,
),
2 =>
array (
0 => 4,
1 => 5,
2 => 6,
),
3 =>
array (
0 => 6,
1 => 5,
2 => 4,
),
)

Categories