Combine two multidimensioal arrays and set one as keys - php

I have these two arrays, which I need to combine
Array (
[0] => Column 1
[1] => Column 2
[2] => Column 3
)
Array (
[0] => Array (
[0] => 111
[1] => 222
[2] => 333
)
[1] => Array (
[0] => 444
[1] => 555
[2] => 666
)
)
into this
Array (
[0] => Array (
[Column 1] => 111
[Column 2] => 222
[Column 3] => 333
)
[1] => Array (
[Column 1] => 444
[Column 2] => 555
[Column 3] => 666
)
)
This is what I have and it works, but I am sure it can be done in a simpler way:
$values = array( array( 1,2,3), array( 4,5,6) );
$fields = array( 'Column 1','Column 2','Column 3');
$i = 0;
$j = 0;
$l = 0;
$rows = array();
$columns = array();
foreach($values as $val) {
$rows[] = $val;
foreach ($fields as &$field) {
$columns[$j][$i] = $field;
$i++;
}
$i = 0;
$j++;
}
foreach($columns as $c){
$result[] = array_combine($c,$rows[$l]);
$l++;
}
What I would like is to clean it up if possible. I do have my struggle with arrays sometimes and this one really messed with my head. :-)

Iterate over the array of arrays and pass each array to array_combine [docs], together with the keys:
$result = array();
foreach($values as $key => $value) {
$result[$key] = array_combine($fields, $value);
}

I think array_combine() like you did is a simple as you can get it. PHP doesn't have a function for everything, but you can make it into whatever your needs are at that moment, so it looks fine to me.
A bit odd you'd put the values and the keys into separate arrays before tho, you could simply do a foreach on the big one I think... or maybe I looked at the code too quickly?

Related

Combining Arrays while merging the values with the same key

I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);

PHP output all possible number combinations

Ok, I've almost finished my script, but my output is not quite as supposed to be. Scripts task is to create all possible number combinations from the sum of all multidimensional array keys. Ive edited few scripts and combined in one script, but I cant seem to get desired output.
Ok, for example, lets say I have array like this one:
$test = array(0 => array(53, 22, 12),
1 => array(94, 84, 94),
2 => array(56, 45, 104)
);
Then I fetch array keys and store them in new array:
foreach ($test as $key => $row) {
$output[] = count($row);
}
for($keycount = 1; $keycount <= count($output); $keycount++){
$newarray[$keycount] = $keycount;
}
And then I count keys from newly created array, so the final combination is based on that number. In aforementioned example, I have 3 combinations, so the final array is supposed to look like this:
111
211
311
121
221
321
131
231
331
112
.
.
.
333
But with my script:
$arraycount = count($newarray);
$maxcombinations = pow($arraycount, $arraycount);
$return = array();
$conversion = array();
foreach ($newarray as $key => $value) {
$conversion[] = $key;
}
for ($i = 0; $i < $maxcombinations; $i++) {
$combination = base_convert($i, 10, $arraycount);
$combination = str_pad($combination, $arraycount, "0", STR_PAD_BOTH);
$return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);
}
echo "<pre>".print_r($return, true)."</pre>";
I'm getting output like this:
Array
(
[0] => Array
(
[0] => 111
)
[1] => Array
(
[0] => 121
)
[2] => Array
(
[0] => 131
)
[3] => Array
(
[0] => 211
)
[4] => Array
(
[0] => 221
)
[5] => Array
(
[0] => 231
)
[6] => Array
(
[0] => 311
)
You are using array like $return[$i][] thus you are getting your output as unexpected
Try
$return[$i] = substr(strtr($combination, $conversion), 1, $arraycount);
Instead of
$return[$i][] = substr(strtr($combination, $conversion), 1, $arraycount);

Combine two different dimensional arrays 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);

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.

Combining arrays with calculation (sum)

I have these two arrays result in print_r:
Array ( [0] => multidesign1 [1] => multidesign1 [2] => multidesign2 [3] => multidesign2 )
Array ( [0] => 30 [1] => 7 [2] => 40 [3] => 1 )
The actual contents should be:
multidesign1 has 30 and 7 so its 37 while multidesign2 has 40 and 1 so its 41.
Can I combine these two arrays so I could come up with multidesign1=>37 and multidesign2=>41 ?
Thanks.
$newArray = array();
foreach(range(0, count($firstArray) - 1) as $index) {
if(isset($newArray[$index])) {
$newArray[$index] += $secondArray[$index];
} else {
$newArray[$index] = $secondArray[$index];
}
}
Is that something like what you're looking for?
$result = array();
foreach ($array1 as $i => $key) {
$result[$key] += $array2[$i];
}

Categories