How to merge two arrays based on same index with same index - php

Actually i have two arrays as given below
$array1=array('0'=>'abc','1'=>'xyz');
$array2=array('0'=>'pqr','1'=>'mno');
I want to two arrays first created with key[0] and second with key[1]. means should look like as follow
$a1=array('0'=>'abc','1'=>'pqr');
$a2=array('0'=>'xyz','1'=>'mno');
The result must be
$a1 = array (
'0' => $array1[0],
'1' => $array2[0]
);
$a2 = array (
'0' => $array1[1],
'1' => $array2[1]
);

You try this code
<?php
$array1=array('0'=>'abc','1'=>'xyz');
$array2=array('0'=>'pqr','1'=>'mno');
foreach($array1 as $key => $val){
$array_name = "a".($key + 1);
${$array_name} = array();
${$array_name}[0] = $array1[$key];
${$array_name}[1] = $array2[$key];
}
var_dump($a1);
var_dump($a2);

Related

Get the index of the same value of a array php

I have an associative array like this [this array is combination of two different arrays]:
I combine arrays and via array_combine() function
$products = array_combine($one_array_key,$second_array_values);
$products = array(
"arn1" =>"A",
"arn2" =>"A",
"arn3" =>"A",
"arn4" =>"B",
"arn5" =>"B",
"arn6" =>"B"
);
So As you can see there are two distinct values from array A and B.
I want two arrays consists of it's keys.
Or in other words: Compare values of associative array and matched values's key will be extract to the other array .
So My expected out is:
$A = array("arn1","arn2","arn3");
$B = array("arn4","arn5","arn6");
My code:
$products = array_combine($one_array_key,$second_array_values);
$products_distinct_values = array_count_values($product);
$products_distinct_values_keys = array_keys($products_distinct_values);
foreach ($products as $key => $value)
{
// what should I need write there, to get the x numbers of array(s), containing *key* of the same *value of array*
}
I SUPER would never use this "variable variables" technique in a professional project, but it does satisfy your brief. I will urge you to find the folly in your XY Problem.
Effectively, the snippet below will synchronously iterate over the two related input arrays and create variably-named result arrays to push values into.
Code: (Demo)
$one_array_key = ['A', 'A', 'A', 'B', 'B', 'B'];
$second_array_values = ['arn1', 'arn2', 'arn3', 'arn4', 'arn5', 'arn6'];
foreach ($one_array_key as $index => $value) {
$$value[] = $second_array_values[$index];
}
var_export($A);
echo "\n---\n";
var_export($B);
Output:
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
)
---
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
)
It makes much more sense to have a statically named variable containing keys and related subarrays. This way you can call array_keys() on the result, if you wish, to find out which groups were found in the original input.
Code: (Demo)
$result = [];
foreach ($one_array_key as $index => $value) {
$result[$value][] = $second_array_values[$index];
}
var_export($result);
Output:
array (
'A' =>
array (
0 => 'arn1',
1 => 'arn2',
2 => 'arn3',
),
'B' =>
array (
0 => 'arn4',
1 => 'arn5',
2 => 'arn6',
),
)
You can use the following PHP code to do that.
<?php
$products = array("arn1"=>"A", "arn2"=>"A", "arn3"=>"A", "arn4"=>"B", "arn5"=>"B", "arn6"=>"B");
$A = array();
$B = array();
foreach ($products as $key => $value)
{
if ($value == "A")
{
array_push ($A, $key);
}
else if ($value == "B")
{
array_push ($B, $key);
}
}
print_r ($A);
print_r ($B);
?>

PHP Sum value of specific key with the same ID inside n numbers of arrays in array

I want to sum the value of one key (qty) if has the same ID of n numbers of arrays inside an array,
in this example I have only 2 arrays but I could have 1000
$a = array(
array(
"id"=>1,
"qty"=>2
),
array(
"id"=>1,
"qty"=>4
)
...n arrays
);
I want the result like this...
$b = array(
array(
"id"=>1,
"qty"=>6
));
I want a function to pass variable $a with n numbers of arrays and returned $b. Thank you
resolved
$result = array();
foreach($array as $k => $v) {
$id = $v['id'];
$result[$id][] = $v['quantity'];
}
$new = array();
foreach($result as $key => $value) {
$new[] = array('id' => $key, 'quanity' => array_sum($value));
}
echo '<pre>';
print_r($new);
?>

Find all array keys that has same value

Is there a simpler way to get all array keys that has same value, when the value is unknown.
The problem with array_unique is that it returns the unique array and thus it doesn't find unique values.
That is, for example, from this array:
Array (
[a]=>1000
[b]=>1
[c]=>1000
)
I want to get this
Array (
[a]=>1000
[c]=>1000
)
Another way around this is, if I could find the lonely values, and then their keys, and then use array_diff
This is what I've got so far, looks awful:
$a = array( 'a' => 1000, 'b' => 1, 'c' => 1000 );
$b = array_flip( array_count_values( $a ) );
krsort( $b );
$final = array_keys( $a, array_shift( $b ) );
Update
Using Paulo Freites' answer as a code base, I could get it working pretty easily, maintainable and easy on eyes kind of way… by using the filtering as a static class method I can get the duplicate values from an array by just calling ClassName::get_duplicates($array_to_filter)
private static $counts = null;
private static function filter_duplicates ($value) {
return self::$counts[ $value ] > 1;
}
public static function get_duplicates ($array) {
self::$counts = array_count_values( $array );
return array_filter( $array, 'ClassName::filter_duplicates' );
}
Taking advantage of closures for a more straightforward solution:
$array = array('a' => 1000, 'b' => 1, 'c' => 1000);
$counts = array_count_values($array);
$filtered = array_filter($array, function ($value) use ($counts) {
return $counts[$value] > 1;
});
var_dump($filtered);
This gave me the following:
array(2) {
["a"]=>
int(1000)
["c"]=>
int(1000)
}
Demo: https://eval.in/67526
That's all! :)
Update: backward-compatible solution
$array = array('a' => 1000, 'b' => 1, 'c' => 1000);
$counts = array_count_values($array);
$filtered = array_filter($array, create_function('$value',
'global $counts; return $counts[$value] > 1;'));
var_dump($filtered);
Demo: https://eval.in/68255
Your implementation has a few issues.
1) If there are 2 of value 1000 and 2 of another value, the array_flip will lose one of the sets of values.
2) If there are more than two different values, the array_keys will only find the one value that occurs most.
3) If there are no duplicates, you will still bring back one of the values.
Something like this works always and will return all duplicate values:
<?php
//the array
$a = array( 'a' => 1000, 'b' => 1, 'c' => 1000 );
//count of values
$cnt = array_count_values($a);
//a new array
$newArray = array();
//loop over existing array
foreach($a as $k=>$v){
//if the count for this value is more than 1 (meaning value has a duplicate)
if($cnt[$v] > 1){
//add to the new array
$newArray[$k] = $v;
}
}
print_r($newArray);
http://codepad.viper-7.com/fal5Yz
If you want to get the duplicates in an array try this:
array_unique(array_diff_assoc($array1, array_unique($array1)))
I found this from:
http://www.php.net/manual/en/function.array-unique.php#95203
at the moment I cant figure out another solution...
// target array
$your_array = array('a'=>1000, 'b'=>1, 'c'=>1000);
// function to do all the job
function get_duplicate_elements($array) {
$res = array();
$counts = array_count_values($array);
foreach ($counts as $id=>$count) {
if ($count > 1) {
$r = array();
$keys = array_keys($array, $id);
foreach ($keys as $k) $r[$k] = $id;
$res[] = $r;
}
}
return sizeof($res) > 0 ? $res : false;
}
// test it
print_r(get_duplicate_elements($your_array));
output:
Array
(
[0] => Array
(
[a] => 1000
[c] => 1000
)
)
example #2: - when you have different values multiplied
// target array
$your_array = array('a'=>1000, 'b'=>1, 'c'=>1000, 'd'=>500, 'e'=>1);
// output
print_r(get_duplicate_elements($your_array));
output:
Array
(
[0] => Array
(
[a] => 1000
[c] => 1000
)
[1] => Array
(
[b] => 1
[e] => 1
)
)
if function result has been assigned to $res variable $res[0] gets an array of all elements from original array with first value found more than once, $res[1] gets array of elements with another duplicated-value, etc... function returns false if nothing duplicate has been found in argument-array.
Try this
$a = array( 'a' => 1, 'b' => 1000, 'c' => 1000,'d'=>'duplicate','e'=>'duplicate','f'=>'ok','g'=>'ok' );
$b = array_map("unserialize", array_unique(array_map("serialize", $a)));
$c = array_diff_key($a, $b);
$array = array("1"=>"A","2"=>"A","3"=>"A","4"=>"B","5"=>"B","6"=>"B");
$val = array_unique(array_values($array));
foreach ($val As $v){
$dat[$v] = array_keys($array,$v);
}
print_r($dat);

Two arrays to one

I have two arrays and I want one, can I add array 2 to array one?
$array1 = array("Germany" => 2, "Belgium"=> 3);
$array2 = array("France" => 4, "Italy"=> 5);
$final_array = {both arrays in one};
is this possible?
Yes, use the array_merge function, like this:
$final_array = array_merge($array1, $array2);
print_r($final_array);
When I run the above script it'll output:
Array (
[Germany] => 2
[Belgium] => 3
[France] => 4
[Italy] => 5
)
Take a quick read here: http://www.php.net/manual/de/function.array-merge.php
Use array_merge like
$final_arr = array_merge($array1 , $array2);
print_r($final_arr);
See this LINK for more
I would like to mention that on duplicated keys array_merge() returns the value from the second array. So, if you have different values with same keys - you should write your own function.
For example:
<?php
$a = array('rund' => '2', 'group' => '3', 'kupon' => 'utre', 'tralala' => 'shtur_kupon');
$b = array('grund' => '2', 'group' => 'ww', 'soup' => '1', 'tralala' => 'fd');
function two_arrays_merge_all_values(array $a, array $b) {
foreach ($b as $b_key => $b_value) {
$a_last_index = count($a);
$current_index = 1;
foreach ($a as $a_key => $a_value) {
if ($a_key === $b_key) {
$unique = uniqid();
$a[$b_key . '_' . $unique] = $b[$b_key];
unset($b[$b_key]);
break;
}
if ($current_index == $a_last_index) {
$a[$b_key] = $b[$b_key];
unset($b[$b_key]);
}
$current_index++;
}
}
return $a;
}

PHP: merge two arrays, distinct on first key, sum second key

I have two arrays:
$array1 = array (a => '501', b => '1');
$array2 = array (a => '501', b => '2');
The merged array should look like this:
$merged_array = array (a => '501', b => '3');
I've tried many suggestions, one of them is:
$sums = array();
foreach (array_keys($array1 + $array2) as $key) {
$sums[$key] = (isset($array[$key]) ? $array[$key] : 0) + (isset($array2[$key]) ? $array2[$key] : 0);
}
but this results in:
$merged_array = array (a => '1002', b => '3');
How should I do this? Any advice is much appreciated
edit: after reading a few comments I realized I should've been more clear. see below
4 arrays, note the duplicates in 'a':
$array1 = array (a => '501', b => '1');
$array2 = array (a => '501', b => '2');
$array3 = array (a => '505', b => '1');
$array4 = array (a => '509', b => '1');
4 merged arrays and serialized should become something like
a:2:{s:1:"a";i:501;s:1:"b";i:3; s:1:"a";i:505;s:1:"b";i:1; s:1:"a";i:509;s:1:"b";i:1;}
so: 2x a => '501' becomes 1x a => '501' and it's 'b' keys become '3' (summed)
and: 1x a=> '505' and b => '1'
and: 1x a=> '509' and b => '1'
$array1 = array (a => '501', b => '1');
$array2 = array (a => '501', b => '2');
function super_merge($a1, $a2)
{
$a = array();
$k_ar = array_keys($a1 + $a2);
foreach ($k_ar as $k)
{
if (isset($a1[$k]) && isset($a2[$k]) && $a1[$k] == $a2[$k])
$a[$k] = $a1[$k];
else
$a[$k] = (isset($a1[$k]) ? $a1[$k] : 0) + (isset($a2[$k]) ? $a2[$k] : 0);
}
return $a;
}
var_dump(super_merge($array1, $array2));
You could build an array with the 'a' value as key and the 'b' value as value
function map_a_to_b($array) {
return array($array['a'] => $array['b'];
}
Apply map_a_to_b to all your input arrays. Then you can merge the arrays recursively:
$merged = array_merge_recursive($array1, $array2, $array3, $array4);
The result will be (for your example):
array ('501' => array('1', '2'),
'505' => '1',
'509' => '1')
Now sum the inner arrays like that:
$summed = array_map(function($item) { return array_sum((array) $item); }, $merged);
And convert the key-value array back to your a/b structure. I don't know how exactly it should look like because I can't read serialized arrays fluently. So if you need help with that, please show the desired output as unserialized array.

Categories