Hi, I am trying to get two arrays elements with the same key to me merged together.
array1 = array(0=>"1", 1=>"2", 2=>"3");
array2 = array(0=>"a", 1=>"b", 2=>"c");
foreach ($array1 as $origKey => &$subArray)
foreach ($array2[$origKey] as $key => $val)
$subArray[$key] = $val;
The ouptut required:
array(0=>"1a", 1=>"2b", 2=>"3c")
Can somebody help me, please?
Use the following function to combine values
function combineValues($a1, $a2){
foreach ($a1 as $k => $v)
$r[$k] = $v . $a2[$k];
return $r;
}
<?
$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");
foreach ($array1 as $origKey => &$subArray)
$new[] = $subArray.$array2[$origKey];
print_r($new);
//Output: Array ( [0] => 1a [1] => 2b [2] => 3c )
Here you go:
<?php
$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");
$sub = [];
foreach ($array1 as $key => $value) {
array_push($sub, $value.$array2[$key]);
}
var_dump($sub);
->
array(3) {
[0]=>
string(2) "1a"
[1]=>
string(2) "2b"
[2]=>
string(2) "3c"
}
your this statement foreach ($array2[$origKey] as $key => $val) is wrong
that part $array[$origkey] coz in foreach $key as $value this basically evaluates whole array so use this way ....
<?php
$array1 = array(0=>"1", 1=>"2", 2=>"3");
$array2 = array(0=>"a", 1=>"b", 2=>"c");
$array3 = array();
for($i=0 ;$i<3 ;$i++)
{
$array3[] = $array1[$i].$array2[$i];
}
foreach($array3 as $merge)
{
echo $merge."<br>";
}
?>
let's get to the point, this will only work for a 1 dimension arrays of any lenghts :
$concatted_array = array(); // the new array
// if the 2 arrays don't have te same lenght, get the largest array
$max_array_length = (count($array1) > count($array2)) ? count($array1) : count($array1);
// loop for the longest array
for ($i=0; $i <$max_array_length ; $i++) {
if($i < count($array1) && $i < count($array2)) // if the element exist for both arrays
{
$concatted_array[$i] = $array1[$i].$array2[$i];
} elseif($i < count($array1)) // if element only exists in $array1
{
$concatted_array[$i] = $array1[$i];
} else // if element only exists in $array2
{
$concatted_array[$i] = $array2[$i];
}
}
var_dump($concatted_array);
Here is the output :
array (size=3)
0 => string '1a' (length=2)
1 => string '2b' (length=2)
2 => string '3c' (length=2)
Now here are some tips just in case you had errors with the code you wrote :
Don't forget the $ before variables.
foreach should be used only on arrays or object, so don't do foreach ($array2[$origKey] as $key => $val) unless $array2[$origKey] is an array or object itself. visit foreach documentation for more info.
Related
I have two array
first array:
Array (
[01-1970] => 0.00
[03-2019] => 4350.00
[05-2019] => 150.00
[06-2019] => 50.00
)
second array:
Array (
[03-2019] => 0.00
[04-2019] => 0.00
[06-2019] => 34.83
)
My expected sum result is:
Array (
[01-1970] => 0.00
[03-2019] => 4350
[04-2019] => 0.00
[05-2019] => 150.00
[06-2019] => 84.83
)
How can achieve this?
You can use array_keys to get the unique from both of the array and then loop through keys to some them
$r = [];
$keys = array_keys($a1+$a2);
foreach($keys as $v){
$r[$v] = (empty($a1[$v]) ? 0 : $a1[$v]) + (empty($a2[$v]) ? 0 : $a2[$v]);
}
Working DEMO
Your best bet is to loop the arrays individually, and sum up the values into a resulting array as you go. We can create a new array that contains the two arrays them to shorten our code a bit (see how we define [$first, $second] as the first loop).
This removes any problems with mixed lengths, and keeps all the keys and values in the array intact.
$result = [];
// Loop over our two arrays, here called $first and $second
foreach ([$first, $second] as $a) {
// Loop over the values in each array
foreach ($a as $k=>$v) {
// If the index is new to the $result array, define it to be zero (to avoid undefined index notices)
if (!isset($result[$k]))
$result[$k] = 0;
// Sum up the value!
$result[$k] += $v;
}
}
print_r($result);
Live demo at https://3v4l.org/X4ijP
You can make use of a function I made:
<?php
function array_sum_multi($arrayOne, $arrayTwo)
{
# get rid of keys
$valuesOne = array_values($arrayOne);
$valuesTwo = array_values($arrayTwo);
//create return array
$output = [];
# loop that shizzle
for ($i = 0; $i < count($valuesOne); $i++)
{
$output[$i] = $valuesOne[$i] + (!empty($valuesTwo[$i]) ? $valuesTwo[$i] : 0);
}
return $output;
}
$result = array_sum_multi([0.00, 4350.00, 150.00, 50.00], [0.00, 0.00, 34.83]);
# then for your keys:
$result = array_combine(array_keys($yourFirstArray), $result);
echo '<pre>'. print_r($result, 1) .'</pre>';
$result = $first_array; // just copy array into result
// scan second array
foreach ($second_array as $k => $v) {
// if key already exists, then add, else just set
$result[$k] = isset($result[$k]) ? ($result[$k] + $v) : $v;
}
// done
print_r($result);
An easy way to implement it would be to loop through each array, and add it to a common array with the same key.
Looping through only one array would result in a lack of a few elements if the first array is smaller than the second one or if some element from the second array are not present in the first one.
So let's just loop through both of them and add it to sum.
$sum = [];
foreach($firstArray as $key => $value){
$sum[$key] = $value + (isset($sum[$key]) ? $sum[$key] : 0.0);
}
foreach($secondArray as $key => $value){
$sum[$key] = $value + (isset($sum[$key]) ? $sum[$key] : 0.0);
}
print_r($sum);
Try this simple method thank you,
$sum = [];
foreach($firstArray as $key => $value){
if(array_key_exists($key,$secondArray)){
$newArray = [$key=>$value+$secondArray[$key]];
$sum = array_merge($sum,$newArray);
}else{
$newArray = [$key=>$value];
$sum = array_merge($sum,$newArray);
}
}
//your final required result
var_dump($sum);
Try this,
$a1 = array (
'01-1970' => 0.00,
'03-2019' => 4350.00,
'05-2019' => 150.00,
'06-2019' => 50.00
);
$a2 = array (
'03-2019' => 0.00,
'04-2019' => 0.00,
'06-2019' => 34.83
);
$sums = array();
foreach (array_keys($a1 + $a2) as $key) {
$sums[$key] = #($a1[$key] + $a2[$key]);
}
echo "<pre>";
print_r($sums);
Here is some other solution you can use.
Cheer!
$sumArray = [];
foreach($firstArray as $key => $value) {
$sumArray[$key] = $value + ($secondArray[$key] ?? 0);
}
Suppose I have an array like this:
$array = array("a","b","c","d","a","a");
and I want to get all the keys that have the value "a".
I know I can get them using a while loop:
while ($a = current($array)) {
if ($a == 'a') {
echo key($array).',';
}
next($array);
}
How can I get them using a foreach loop instead?
I've tried:
foreach ($array as $a) {
if ($a == 'a') {
echo key($array).',';
}
}
and I got
1,1,1,
as the result.
If you would like all of the keys for a particular value, I would suggest using array_keys, using the optional search_value parameter.
$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );
Where $result becomes
Array (
[0] => Foo
[1] => Bar
)
If you wish to use a foreach, you can iterate through each key/value set, adding the key to a new array collection when its value matches your search:
$array = array("a","b","c","d","a","a");
$keys = array();
foreach ( $array as $key => $value )
$value === "a" && array_push( $keys, $key );
Where $keys becomes
Array (
[0] => 0
[1] => 4
[2] => 5
)
You can use the below to print out keys with specific value
foreach ($array as $key=>$val) {
if ($val == 'a') {
echo $key." ";
}
}
here's a simpler filter.
$query = "a";
$result = array_keys(array_filter($array,
function($element)use($query){
if($element==$query) return true;
}
));
use
foreach($array as $key=>$val)
{
//access the $key as key.
}
How can i do an array_merge on an associative array, like so:
Array 1:
$options = array (
"1567" => "test",
"1853" => "test1",
);
Array 2:
$option = array (
"none" => "N/A"
);
So i need to array_merge these two but when i do i get this (in debug):
Array
(
[none] => N/A
[0] => test
[1] => test1
)
try using :
$finalArray = $options + $option .see http://codepad.org/BJ0HVtac
Just check the behaviour for duplicate keys, I did not test this. For unique keys, it works great.
<?php
$options = array (
"1567" => "test",
"1853" => "test1",
);
$option = array (
"none" => "N/A"
);
$final = array_merge($option,$options);
var_dump($final);
$finalNew = $option + $options ;
var_dump($finalNew);
?>
Just use $options + $option!
var_dump($options + $option);
outputs:
array(3) {
[1567]=>
string(4) "test"
[1853]=>
string(5) "test1"
["none"]=>
string(3) "N/A"
}
But be careful when there is a key collision. Here is what the PHP manual says:
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
$final_option = $option + $options;
I was looking to merge two associative arrays together, adding the values together if the keys were the same. If there were keys unique to either array, these would be added into the merged array with their existing values.
I couldnt find a function to do this, so made this:
function array_merge_assoc($array1, $array2)
{
if(sizeof($array1)>sizeof($array2))
{
echo $size = sizeof($array1);
}
else
{
$a = $array1;
$array1 = $array2;
$array2 = $a;
echo $size = sizeof($array1);
}
$keys2 = array_keys($array2);
for($i = 0;$i<$size;$i++)
{
$array1[$keys2[$i]] = $array1[$keys2[$i]] + $array2[$keys2[$i]];
}
$array1 = array_filter($array1);
return $array1;
}
Reference: http://www.php.net/manual/en/function.array-merge.php#90136
when array_merge doesn't work, then simply do
<?php
$new = array();
foreach ($options as $key=>$value) $new[$key] = $value;
foreach ($option as $key=>$value) $new[$key] = $value;
?>
or switch the two foreach loops depending on which array has higher priority
This code could be used for recursive merge:
function merge($arr1, $arr2){
$out = array();
foreach($arr1 as $key => $val1){
if(isset($arr2[$key])){
if(is_array($arr1[$key]) && is_array($arr2[$key])){
$out[$key]= merge($arr1[$key], $arr2[$key]);
}else{
$out[$key]= array($arr1[$key], $arr2[$key]);
}
unset($arr2[$key]);
}else{
$out[$key] = $arr1[$key];
}
}
return $out + $arr2;
}
If arrays having same keys then use array_merge_recursive()
$array1 = array( "a" => "1" , "b" => "45" );
$array2 = array( "a" => "23" , "b" => "33" );
$newarray = array_merge_recursive($array1,$array2);
The array_merge_recursive() wont overwrite, it just makes the value as an array.
I have an array like this:
$months = Array (
"may" =>
Array (
"A" => 101,
"B" => 33,
"C" => 25
),
"june" =>
Array (
"A" => 73,
"B" => 11,
"D" => 32
),
"july" =>
Array (
"A" => 45,
"C" => 12
)
);
I want to get an array like this:
Array ( ['all'] =>
Array (
[A] => 219
[B] => 44
[C] => 37
[D] => 32
)
)
I wrote a function with 2 parameters (the two arrays to join) and it worked, but I fail, when I try to make it possible to call it with more than 2 arrays. I tried to do it via recursion:
function array_merge_elements(){
$arg_list = func_get_args();
$array1 = $arg_list[0];
$array2 = $arg_list[1];
$keys = array_unique(array_merge(array_keys($array1), array_keys($array2)));
$result_array = array();
foreach($keys as $key) {
$result_array["$key"] = 0;
if(!empty($array1[$key])) {
$result_array["$key"] += $array1[$key];
}
if(!empty($array2[$key])) {
$result_array["$key"] += $array2[$key];
}
}
if(func_num_args() == 2) {
return $result_array;
} else {
unset($arg_list[0]);
unset($arg_list[1]);
return array_merge_elements($result_array, $arg_list);
}
}
The problem seems to be, that calling the function with (array1, arglist) is not the same as calling the function with (array1, array2, array3) etc.
What's wrong with just doing (demo)
foreach ($months as $month) {
foreach ($month as $letter => $value) {
if (isset($months['all'][$letter])) {
$months['all'][$letter] += $value;
} else {
$months['all'][$letter] = $value;
}
}
}
print_r($months['all']);
or - somewhat less readable due to the ternary operation (demo):
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($months));
foreach ($iterator as $letter => $value) {
isset($months['all'][$letter])
? $months['all'][$letter] += $value
: $months['all'][$letter] = $value;
}
print_r($months['all']);
If you'd split off the first two entries of your found arguments; you can use the resulting array in a call with this function: Call_user_func_array
for fellow googlers out there, here's the answer to the original question
Assume we have a function that adds two arrays together:
function array_plus($a, $b) {
foreach($b as $k => $v)
$a[$k] = (isset($a[$k]) ? $a[$k] : 0) + $v;
return $a;
}
this is how to apply this function to a set of arrays
$sum = array_reduce($months, 'array_plus', array());
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.