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);
}
Related
I'm trying to get the name of an array once I have found a specific value.
Specifically I'm looking to get the highest and lowest values within my array for a certain key, once I have those values I then need to get the name of the array holding those values.
My array looks like this -
Array
(
[123456] => Array
(
[value1] => 0.524
[value2] => 0.898
[value3] => -6.543
)
[246810] => Array
(
[value1] => 0.579
[value2] => 0.989
[value3] => -5.035
)
I have gotten the max value using this code -
max(array_column($statsArr, 'value1'));
This, correctly, gives me the value "0.579". I now need to get the value of the array holding this information so in this case I also want to get the value "246810". I don't know how to do this though, any help would be appreciated!
Iterate over your array with a simple foreach and save required key:
$max = 0;
$founded_key = false;
foreach ($array as $key => $value) {
if ($max < $value['value1']) {
$max = $value['value1'];
$founded_key = $key;
}
}
echo $founded_key, ' - ', $max;
For these kinds of problems I like using array_reduce. max is itself an array reduce operation which takes an array and returns a single value, PHP just offers it out of the box as convenience since it's a very common operation.
Here's an example code:
$array = array(
123456 => array(
'value1' => 0.524,
'value2' => 0.898,
'value3' => -6.543
),
246810 => array(
'value1' => 0.579,
'value2' => 0.989,
'value3' => -5.035
)
);
$maxKey = array_reduce(array_keys($array), function ($carry, $key) use ($array) {
if ($carry === null) {
return $key;
}
return $array[$key]['value1'] > $array[$carry]['value1'] ? $key : $carry;
}, null);
$maxValue = $array[$maxKey]['value1'];
Working example: http://sandbox.onlinephpfunctions.com/code/ecd400ffec91a6436c2fb5ee0410658e22772d4b
function getMax($array, $field) {
$maxValue = null;
$maxKey = null;
foreach($array as $key => $content) {
if (is_null($maxValue) || $content[$field] > $maxValue) {
$maxValue = $content[$field];
$maxKey = $key;
}
}
return [$maxValue, $maxKey];
}
You can search for the maximum value in the array_column.
I first prepare the array_column with correct keys by combining it, then find the max like you do.
Then we can array_search the value.
$value1 = array_combine(array_keys($statsArr), array_column($statsArr, 'value1'));
$max = max($value1);
echo $max . PHP_EOL;
$array = $statsArr[array_search($max, $value1)];
var_dump($array);
https://3v4l.org/Q9gOX
Alternatively you can array_values the $statsArr to make it 0 indexed just like the array_column.
$value1 = array_column($statsArr, 'value1');
$max = max($value1);
echo $max . PHP_EOL;
$array = array_values($statsArr)[array_search($max, $value1)];
var_dump($array);
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.
I am wondering if I could explain this.
I have a multidimensional array , I would like to get the count of particular value appearing in that array
Below I am showing the snippet of array . I am just checking with the profile_type .
So I am trying to display the count of profile_type in the array
EDIT
Sorry I've forgot mention something, not something its the main thing , I need the count of profile_type==p
Array
(
[0] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => p
[birthyear] => 1978
[is_elite] => 0
)
)
[1] => Array
(
[Driver] => Array
(
[id] => 4
[profile_type] => d
[birthyear] => 1972
[is_elite] => 1
)
)
)
Easy solution with RecursiveArrayIterator, so you don't have to care about the dimensions:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$counter = 0
foreach ($iterator as $key => $value) {
if ($key == 'profile_type' && $value == 'p') {
$counter++;
}
}
echo $counter;
Something like this might work...
$counts = array();
foreach ($array as $key=>$val) {
foreach ($innerArray as $driver=>$arr) {
$counts[] = $arr['profile_type'];
}
}
$solution = array_count_values($counts);
I'd do something like:
$profile = array();
foreach($array as $elem) {
if (isset($elem['Driver']['profile_type'])) {
$profile[$elem['Driver']['profile_type']]++;
} else {
$profile[$elem['Driver']['profile_type']] = 1;
}
}
print_r($profile);
You may also use array_walk($array,"test") and define a function "test" that checks each item of the array for 'type' and calls recursively array_walk($arrayElement,"test") for items of type 'array' , else checks for the condition. If condition satisfies, increment a count.
Hi You can get count of profuke_type==p from a multi dimensiona array
$arr = array();
$arr[0]['Driver']['id'] = 4;
$arr[0]['Driver']['profile_type'] = 'p';
$arr[0]['Driver']['birthyear'] = 1978;
$arr[0]['Driver']['is_elite'] = 0;
$arr[1]['Driver']['id'] = 4;
$arr[1]['Driver']['profile_type'] = 'd';
$arr[1]['Driver']['birthyear'] = 1972;
$arr[1]['Driver']['is_elite'] = 1;
$arr[2]['profile_type'] = 'p';
$result = 0;
get_count($arr, 'profile_type', 'd' , $result);
echo $result;
function get_count($array, $key, $value , &$result){
if(!is_array($array)){
return;
}
if($array[$key] == $value){
$result++;
}
foreach($array AS $arr){
get_count($arr, $key, $value , $result);
}
}
try this..
thanks
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.
}
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.