Merge two arrays, replacing values of same key - php

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)

Related

PHP - Sort Array By SubArray Value By Maintaining original Array key

I would like to Sort an Array with its sub array value ("Name") but keeping its original array key.
default Array:
Array (
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
By using array_multisort, I can able to get following Array:
Array(
[0] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[1] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[2] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
But what i need is,
Array(
[323] => Array
(
[color] =>
[name] => 7
[nbr] => 2
[url_name] => taille-7
[meta_title] =>
)
[251] => Array
(
[color] =>
[name] => 8
[nbr] => 1
[url_name] => taille-8
[meta_title] =>
)
[127] => Array
(
[color] =>
[name] => 34
[nbr] => 2
[url_name] => taille-34
[meta_title] =>
)
);
Thanks in adv :)
I would go with uasort, it looks much simpler to me:
// $arr is your Array
uasort($arr, function ($a, $b) {
return $a['name'] - $b['name'];
});
Here is an example: http://sandbox.onlinephpfunctions.com/code/a9f2d1e9702834b3a35206125429739222770301
$arr being your array:
//obtain list of values to sort by
foreach ($arr as $id => $value) {
$names[$id] = $value['name'];
}
$keys = array_keys($arr);
array_multisort(
$names, SORT_ASC, SORT_NUMERIC, $arr, $keys
);
$result = array_combine($keys, $arr);
You were probably missing the last step combining the array with given keys.
$arr assuming your array containing numeric keys and sort it by using array_multisort.
array_multisort will return sorted array.
array_combine will combine your original keys with sorted array.
Use:
$result = array_sort_by_column_preserve_keys($arr);
echo '<pre>';print_r($result);echo '</pre>';
Method :
function array_sort_by_column_preserve_keys($arr) {
$ar2 = [];
foreach($arr as $key => $sub) {
$ar2[ $key ] = $sub;
}
$keys = array_keys($arr);
array_multisort($ar2, SORT_ASC, SORT_NUMERIC, $arr, $keys);
return $result = array_combine($keys, $arr);
}
Please try this,
$array=array(
"251" => array(
"color" => "",
"name" => 8,
"nbr" => 1,
"url_name" => "taille-8",
"meta_title" => ""),
"323" => array(
"color" => "",
"name" => 7,
"nbr" => 2,
"url_name" => "taille-7",
"meta_title" => ""),
"127" => array(
"color" => "",
"name" => 34,
"nbr" => 2,
"url_name" => "taille-34",
"meta_title" => ""),
);
function swapArray( &$arr,$firstPos,$secondPos){
//echo PHP_EOL."swap: ".$firstPos.", ".$secondPos.PHP_EOL;
foreach($arr[$firstPos] as $k=>$v){
//echo PHP_EOL.$k." => ".$v.PHP_EOL;
$tmp=$v;
$arr[$firstPos][$k]=$arr[$secondPos][$k];
$arr[$secondPos][$k]=$tmp;
}
}
var_dump($array);
$keys=array(); // store all key values
$num=count($array);
foreach($array as $key=>$tmpArray)
$keys[]=$key;
//var_dump($keys);
for($i=0; $i<$num; $i++){
for($j=$i+1; $j<$num; $j++){
if($array[$keys[$i]]["name"]>$array[$keys[$j]]["name"]){
swapArray($array,$keys[$i],$keys[$j]);
}
}
}
var_dump($array);

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

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

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

Multidimensional Array Find and Update The Value using PHP

I can't get suitable title for this thread (help me). I can't describe this problem so here the example of my problem.
My array :
Array ( [0] => Array ( [answer] => a [score] => 3 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3)
[3] => Array ( [answer] => a [score] => 4 ))
...
And I wanna get an output like this :
Array ( [0] => Array ( [answer] => a [score] => 7 )
[1] => Array ([answer] => b [score] => 4 )
[2] => Array ( [answer] => h [score] => 3))
...
You can see a change of score subkey in index key 0. This is happen because there is two value 'a' in answer subkey from index key 0 and 3. The score changed to 7 because of the sum of both (3+4). Really I don't have an idea for this, sorry for my english and thanks for help.
Feel free to comment. :)
$merged = array();
foreach ($array as $answer) {
if (isset($merged[$answer['answer']])) {
$merged[$answer['answer']]['score'] += $answer['score'];
} else {
$merged[$answer['answer']] = $answer;
}
}
var_dump($merged);
Check this answer, not using loop :
$arr = array ( array ( 'answer' => 'a', 'score' => 3 ),
array ( 'answer' => 'b', 'score' => 4 ),
array ( 'answer' => 'h', 'score' => 3),
array ( 'answer' => 'a', 'score' => 4 ));
$t = array_reduce($arr, function($result, $item) {
if(array_key_exists($item['answer'],$result)){
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']+$result[$item['answer']]['score']);
}
else{
$result[$item['answer']] = array('answer' => $item['answer'], 'score' => $item['score']);
}
return $result;
},array());
echo "<pre>";
print_r($t);
Output :
Array
(
[a] => Array
(
[answer] => a
[score] => 7
)
[b] => Array
(
[answer] => b
[score] => 4
)
[h] => Array
(
[answer] => h
[score] => 3
)
)
I though of using a temporary array:
/* Current array */
$array = array(
array("answer" => "a", "score" => 3),
array("answer" => "b", "score" => 4),
array("answer" => "h", "score" => 3),
array("answer" => "a", "score" => 4)
);
/* Using a temporary array */
$tmp_array = array();
foreach($array as $subarray){
if(array_key_exists($subarray["answer"], $tmp_array)){
$tmp_array[$subarray["answer"]] += $subarray["score"];
}else{
$tmp_array[$subarray["answer"]] = $subarray["score"];
}
}
/* Creating a new formatted array */
$new_array = array();
foreach($tmp_array as $key => $value){
$new_array[] = array("answer" => $key, "score" => $value);
}
print_r($new_array);

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