Combine two different dimensional arrays PHP - php

I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
)
)
Array 2:
Array2
(
[0] => 5
[1] => 8
)
I want something like this:
Array
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
[Qty] => 5
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
[Qty] => 8
)
)
Basically the first array is the information I got from a SQL table. The second array contains the quantity for the products sold. I now want to combine these two array together and use the combined array to create a new table. Since these two arrays have different dimensions. I'm not sure how to do it. Here is my try:
$i = 0;
foreach($array1 as $row)
{
$newarray = array_merge($row,$array2[$i]);
$i++;
}

Might be a simpler way, but for fun without foreach:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);

The simplest way is:
$i = 0;
foreach($array1 as &$row) {
$row['Qty'] = $array2[$i++];
}
Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
$row['Qty'] = $array2[$k];
}

If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
$array1[$index]['Qty'] = $quantity;
}
And it´s done!
If you want to keep the original $array1 untouched, you can make a copy before the foreach.

Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.
$array3 = [];
foreach($array1 as $key => $val) {
$array3[] = [
'id' => $val['id'],
'price' => $val['price'],
'purchase_time' => $val['purchase_time'],
'Qty' => $array2[$key]
];
}
print_r($array3);

Related

Combine values by key in single array

Nothing really does exactly what I want to achieve. I have the following array:
Array(
[0] => Array
(
[chicken] => 7
)
[1] => Array
(
[cheese] => 9
)
[2] => Array
(
[marinade] => 3
)
[3] => Array
(
[cookbook] => 7
)
[4] => Array
(
[chicken] => 11
)
[5] => Array
(
[cheese] => 6
)
[6] => Array
(
[marinade] => 12
)
)
I want to sum all values by their key. If the key is multiple times in the array, like chicken, I want to sum the values.
array
(
[chicken] => 18,
[cheese] => 16
... etc
)
So you'd first need a loop to iterate through the first array to get the second-level arrays. Then you can get the current key and value from each of those arrays, summing the values in a new array associated by the key.
// where the sums will live
$sum = [];
foreach($array as $item) {
$key = key($item);
$value = current($item);
if (!array_key_exists($key, $sum)) {
// define the initial sum of $key as 0
$sum[$key] = 0;
}
// add value to the sum of $key
$sum[$key] += $value;
}
Here simple example i hope it's help you.
$result = array();
foreach($data as $key => $value)
{
$valueKey = key($value);
$result[$valueKey] += $value[$valueKey];
}

Count instances of value/key in merged arrays and set value by count

I am looking at trying to do an array_merge with these arrays but I need to be able to count how many times a particular value in the array appears and give me that data back.
Here are the original arrays
Array
(
[0] => this
[1] => that
)
Array
(
[0] => this
[1] => that
[2] => some
)
Array
(
[0] => some
[1] => hello
)
Ultimately I would like it to look like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
That would ultimately allow me to get the key and value I need. I tried 'array_unique` in this process but realized that I may not be able to count the instances of each array that they appear since this would just simple remove them all but one.
I tried something list this
$newArray = array_count_values($mergedArray);
foreach ($newArray as $key => $value) {
echo "$key - <strong>$value</strong> <br />";
}
but I am getting results like this
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
[this] => 3
[that] => 3
[some] => 3
[hello] = > 2
[this] => 2
[that] => 2
[some] => 2
[hello] = > 1
)
Use array_count_values():
$a1 = array(0 => 'this', 1 => 'that');
$a2 = array(0 => 'this', 1 => 'that', 2 => 'some');
$a3 = array(0 => 'some', 1 => 'hello');
// Merge arrays
$test = array_merge($a1,$a2,$a3);
// Run native function
$check = array_count_values($test);
echo '<pre>';
print_r($check);
echo '</pre>';
Gives you:
Array
(
[this] => 2
[that] => 2
[some] => 2
[hello] => 1
)
EDIT: As noted by AlpineCoder:
"This will work only in the case of input arrays using numeric (or unique) keys (since array_merge will overwrite values for the same non-integer key)."
$res = array();
foreach ($arrays as $array) {
foreach ($array as $val) {
if (isset($res[$val])) {
$res[$val]++;
} else {
$res[$val] = 1;
}
}
}
As tyteen4a03 mentioned, use nested foreach loops:
$arr1 = array('foo', 'bar');
$arr2 = array('foo', 'bar', 'baz');
$arr3 = array('baz', 'bus');
$result = array();
foreach(array($arr1, $arr2, $arr3) as $arr) {
foreach ($arr as $value) {
if (!isset($result[$value])) {
$result[$value] = 0;
}
++$result[$value];
}
}
print_r($result);
The outer foreach goes through each set of items (i.e. each array) and the inner foreach loop goes through each item in each set. If the item isn't in the $result array yet, create the key there.
Result:
Array
(
[foo] => 2
[bar] => 2
[baz] => 2
[bus] => 1
)

Combine two arrays into a single array based on a common column value

I am trying to combine two arrays while respecting their shared value.
$array1 = array(
array("id" => "1","name"=>"John"),
array("id" => "2","name"=>"Peter"),
array("id" => "3","name"=>"Tom"),
array("id" => "12","name"=>"Astro")
);
$array2 = array(
array("id" => "1","second_name"=>"Lim"),
array("id" => "2","second_name"=>"Parker"),
array("id" => "3","second_name"=>"PHP")
);
My expected output:
$result = array(
array("id" => "1","name"=>"John","second_name"=>"Lim"),
array("id" => "2","name"=>"Peter","second_name"=>"Parker"),
array("id" => "3","name"=>"Tom","second_name"=>"PHP"),
array("id" => "12","name"=>"Astro")
);
I have made a try by
$arraycomb = array_unique(array_merge($array1,$array2), SORT_REGULAR);
My output is:
Array
(
[0] => Array
(
[id] => 1
[name] => John
)
[1] => Array
(
[id] => 2
[name] => Peter
)
[2] => Array
(
[id] => 3
[name] => Tom
)
[3] => Array
(
[id] => 12
[name] => Astro
)
[4] => Array
(
[id] => 1
[second_name] => Lim
)
[5] => Array
(
[id] => 2
[second_name] => Parker
)
[6] => Array
(
[id] => 3
[second_name] => PHP
)
)
How can I combine the key value inside same array? or how can I bring the expected output?
Note: I am trying for value instead of key ref: PHP Array Merge two Arrays on same key
Alternatively, you could use a foreach in this case then merge them if they share the same id key
With using reference &
foreach($array1 as &$value1) {
foreach ($array2 as $value2) {
if($value1['id'] == $value2['id']) {
$value1 = array_merge($value1, $value2);
}
}
}
echo '<pre>';
print_r($array1);
You can use array_map() for this. Try this -
function modifyArray($a, $b)
{
if (!empty($a) && !empty($b)) {
return array_merge($a, $b);
} else if (!empty($a) && empty($b)) {
return $a;
} else if (empty($a) && !empty($b)) {
return $b;
}
}
$new = array_map("modifyArray", $array1, $array2);
var_dump($new);
It will generate the new array will all the values in both arrays.if the first array's element is empty then the second array will be merged and vice-versa.
Assign temporary first level keys to your first array to aid in identifying rows. Then loop the second array and append the desired column value to the appropriate group. Re-index the array after looping with array_values().
Code: (Demo)
$result = array_column($array1, null, 'id');
foreach ($array2 as $row) {
$result[$row['id']]['second_name'] = $row['second_name'];
}
var_export(array_values($result));
This is a more direct approach than brute force scanning arrays with nested loops.
If all ids in the second array exist in the first array, then the following simpler line can be written inside the body of the foreach().
$result[$row['id']] += $row;

php array find duplicates, sum them up & delete duplicates

i have an array:
Array
(
[0] => Array
(
[setid] => 2
[income] => 100
)
[1] => Array
(
[setid] => 2
[income] => 120
)
[2] => Array
(
[setid] => 3
[income] => 700
)
)
i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:
Array
(
[0] => Array
(
[setid] => 2
[income] => 220
)
[1] => Array
(
[setid] => 3
[income] => 700
)
)
does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?
thanks and greetings
Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.
$result = array();
foreach ($array as $val) {
if (!isset($result[$val['setid']]))
$result[$val['setid']] = $val;
else
$result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array
This should work:
$values = array();
foreach($array as $val) {
if(isset($values[$val['setid']])) {
$values[$val['setid']] += $val['income'];
} else {
$values[$val['setid']] = $val['income'];
}
}
//all values are now in $values array, keys are setid and values are income
Write your own function, that's no long road at all.
$result = array_reduce($originalArray, function($memo, $item){
isset($memo[$item['setid']])
? $memo[$item['setid']] = $item['income']
: $memo[$item['setid']] += $item['income'];
return $memo;
}, []);
You should use the array_unique function that php's official site offers.
An example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)
To sum the duplicated values you can use the array_count_values function:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output would be:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

Sum multidimensional associative array values while preserving key names

There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.

Categories