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;
}
Related
I have 2 arrays a and b which may or may not have similar values.
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
I need to check whether the keys that are there in both the arrays contains same values or not using the array functions itself. Please help me.
NB: Array $a is always the parent array. If any key has to be popped, it would be only from $a.
You can use the following comparison based on array_intersect_assoc:
$b == array_intersect_assoc($a, $b)
This will be true when all of the $b key/value pairs occur in $a, false otherwise.
Use this code:
Use: array_diff_key
Remove duplicate key:
<?php
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
$c = array_diff_key($a, $b);
print_r($c); //Array ( [id] => 1 )
?>
Get duplicate key:
Use: array_intersect_key
<?php
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
print_r(array_duplicate_keys($a, $b)); //Array ( [0] => name [1] => age )
?>
Get duplicate key and value:
<?php
function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}
$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
}
}
}
return $dups;
}
print_r(get_keys_for_duplicate_values($a, $b));
//Array ( [id] => 1 [name] => John Doe [age] => 35 )
?>
If $b can have keys not present in $a, you can use array_intersect_key two times, with arguments in reversed order and check if both results are the same:
$ab = array_intersect_key($a, $b);
$ba = array_intersect_key($b, $a);
$allValuesEqual = ($ab == $ba);
use this:"it compare both key and value"
$result=array_diff_assoc($a1,$a2); //<-Compare both key and value, gives new array
example:
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","b"=>"pink");
$result=array_diff_assoc($a1,$a2);
print_r($result);
//result will be
Array ( [b] => green )
How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>
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.
I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same order as the first array.
Is there a function that can quickly do this?
I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?
$arr1 = array(
'a' => '42',
'b' => '551',
'c' => '512',
'd' => 'gge',
) ;
$arr2 = array(
'd' => 'ordered',
'b' => 'is',
'c' => 'now',
'a' => 'this',
) ;
$arr2ordered = array() ;
foreach (array_keys($arr1) as $key) {
$arr2ordered[$key] = $arr2[$key] ;
}
You can use array_replace
$arr1 = [
'x' => '42',
'y' => '551',
'a' => '512',
'b' => 'gge',
];
$arr2 = [
'a' => 'ordered',
'x' => 'this',
'y' => 'is',
'b' => 'now',
];
$arr2 = array_replace($arr1, $arr2);
$arr2 is now
[
'x' => this,
'y' => is,
'a' => ordered,
'b' => now,
]
foreach(array_keys($array1) as $key)
{
$tempArray[$key] = $array2[$key];
}
$array2 = $tempArray;
I am not completely sure if this is what your after. anyways as long as the the array remains the same size, than this should work for you.
$gamey = array ("wow" => "World of Warcraft", "gw2" => "Guild Wars2", "wiz101" => "Wizard 101");
$gamex = array ("gw2" => "best game", "wiz101" => "WTF?", "wow" => "World greatest");
function match_arrayKeys ($x, $y)
{
$keys = array_keys ($x);
$values = array_values ($y);
for ($x = 0; $x < count ($keys); $x++)
{
$newarray [$keys[$x]] = $y[$keys[$x]];
}
return $newarray;
}
print_r (match_arrayKeys ($gamey, $gamex));
Output
[wow] => World greatest
[gw2] => best game
[wiz101] => WTF?
Try this
CODE
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
OUTPUT
a = orange
b = banana
c = apple
d = lemon
Check the php manual for ksort()
My array:
$data = array('two' => 2, 'one' => 1, 'three' => 3);
Now, with when I iterate the array, the first value that will come up will probably be
$data['two'] // = 2 # index[0]
right?
What if I want to move the $data[1] to the position of $data[0] ?
To rephrase:
How do I make the array look like this (so that 'one' comes up at $data[0])
$data = array('one' => 1, 'two' => 2, 'three' => 3
Why do I need this?
I use code igniter, the table->generate built-in function takes an assoc array and creates a table but offers no method of arranging the columns. This is why I would like to move the columns in the source array.
Two possible solutions (without using array_splice):
1) Create a new array with the new order of the keys.
$new_keys = array('one', 'two', 'three');
$new_data = array();
foreach ($new_keys as $key) {
$new_data[$key] = $data[$key];
}
$data = $new_data;
2) Move the element one upfront, remove it from $data and copy the rest of the array.
function rearrangeData($data) {
$result['one'] = $data['one'];
unset($data['one']);
return array_merge($result, $data);
}
$data = rearrangeData($data);
Take a look at daniele centamore's comment on PHP's array_splice() function, where he provides a couple of functions for moving the elements in an non-associative array.
<?php
// $input (Array) - the array containing the element
// $index (int) - the index of the element you need to move
function moveUp($input,$index) {
$new_array = $input;
if((count($new_array)>$index) && ($index>0)){
array_splice($new_array, $index-1, 0, $input[$index]);
array_splice($new_array, $index+1, 1);
}
return $new_array;
}
function moveDown($input,$index) {
$new_array = $input;
if(count($new_array)>$index) {
array_splice($new_array, $index+2, 0, $input[$index]);
array_splice($new_array, $index, 1);
}
return $new_array;
}
$input = array("red", "green", "blue", "yellow");
$newinput = moveUp($input, 2);
// $newinput is array("red", "blue", "green", "yellow")
$input = moveDown($newinput, 1);
// $input is array("red", "green", "blue", "yellow")
?>
See ksort and uksort.
Here's a working example:
<?php
$data = array('two' => 2, 'one' => 1, 'three' => 3);
print_r($data);
ksort($data);
echo "ksort:\n";
print_r($data);
uksort($data,'cmp');
echo "uksort:\n";
print_r($data);
function cmp($a, $b)
{
$num=' one two three four five six seven eight nine ten';
$ai = stripos($num,$a);
$bi = stripos($num,$b);
if ($ai>0 && $bi>0) {
return ($ai > $bi) ? 1 : -1;
}
return strcasecmp($a, $b);
}
Output:
Array
(
[two] => 2
[one] => 1
[three] => 3
)
ksort:
Array
(
[one] => 1
[three] => 3
[two] => 2
)
uksort:
Array
(
[one] => 1
[two] => 2
[three] => 3
)
Run this:
http://codepad.org/yAK1b1IP
PHP has 13 functions for sorting arrays, by key, by value, by user-defined functions where you can specify that "one" comes before "two". There's also array_shift, array_unshift, array_push and array_pop for moving things onto or off the front or end of the array. You can build a whole new array from the existing one.
I think, you should use asort function:
$data = array('two' => 2, 'one' => 1, 'three' => 3);
$dataOrdered = $data;
asort($dataOrdered);
Run this code