Merge values from different arrays to one with the same key [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
I have two arrays:
Array
(
[0] => 5
[1] => 4
)
Array
(
[0] => BMW
[1] => Ferrari
)
And I would like to have that result. Merge the values with the same key
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
How could I do that? Is there any native PHP function that does this? I tried array_merge_recursive and array_merge but did not get the expected result

As to #splash58 comment:
You can use array-map. Here an example:
$array = [["5", "4"], ["BMW", "Ferrari"]];
$res = array_map(null, ...$array);
Now res will contain:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)
If the array in 2 different var you can use:
$res= array_map(null, ["5", "4"], ["BMW", "Ferrari"]);

<?php
$a = array();
$a[0] = '5';
$a[1] = '4';
$b = array();
$b[0] = 'BMW';
$b[1] = 'Ferrari';
merge_by_key($a, $b);
function merge_by_key($a, $b){
$c = array();
fill_array($c,$a);
fill_array($c,$b);
print_r($c);
}
function fill_array(&$c, $a) {
foreach ($a as $key => $value){
if(isset($c[$key])) {
array_push($c[$key], $value);
} else {
$c[$key] = array($value);
}
}
}
Output:
Array
(
[0] => Array
(
[0] => 5
[1] => BMW
)
[1] => Array
(
[0] => 4
[1] => Ferrari
)
)

You can use array_map with null as the first argument (there is an example in the manual), to get your desired result:
<?php
$nums = [0 => 5, 1 => 4];
$cars = [0 => 'BMW', 1 => 'Ferrari'];
var_export(array_map(null, $nums, $cars));
Output:
array (
0 =>
array (
0 => 5,
1 => 'BMW',
),
1 =>
array (
0 => 4,
1 => 'Ferrari',
),
)
Note that the following input would give the same result:
$nums = ['puff' => 5, 'powder' => 4];
$cars = ['powder' => 'BMW', 'puff' => 'Ferrari'];
It is the order, not the keys, that determine the pairings in the result when using array_map as above.
To associate by key using foreach (note order of $cars):
<?php
$nums = [0 => 5, 1 => 4];
$cars = [1 => 'Ferrari', 0 => 'BMW'];
foreach($nums as $k => $num)
$result[] = [$num, $cars[$k]];
var_export($result);
Results also in the desired output.

Related

PHP array merge two arrays on same key What should I do [duplicate]

This question already has answers here:
Transpose multidimensional array and join values with commas [duplicate]
(2 answers)
Closed 10 months ago.
Input: $a as input array and $b as formatting array
$a = Array
(
[0] => 1
[1] => 5
[2] => 7
)
$b = Array
(
[0] => 5
[1] => 3
[2] => 4
)
$result = Array
(
[0] => 1,5
[1] => 5,3
[2] => 7,4
)
How do I merge 2 arrays to achive the result above with PHP?
Use the array_map function as:
<?php
$a = [1, 5, 7];
$b = [5, 3, 4];
$result = array_map(null, $a, $b); // passing null as the callback to perform a zip operation on multiple arrays
print_r($result);
?>
Alternative solution, :P
<?php
$a = [1, 5, 7];
$b = [5, 3, 4];
$result = [];
foreach($a as $k => $v) {
$result[$k] = [$v, $b[$k]];
}
print_r($result);
?>
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 5
)
[1] => Array
(
[0] => 5
[1] => 3
)
[2] => Array
(
[0] => 7
[1] => 4
)
)

How to concatenate arrays element recursively [duplicate]

This question already has answers here:
Joining similar data from two indexed arrays
(2 answers)
Closed 5 months ago.
I'm working on a project and I'm stacked since 2 days, this is my problem: I have two arrays and want to retrieve the second item in each object in Array_2 and concatenate it to the content of each object in first Array_1 in PHP.
Array_1
[[1453274700000,24011],[1453275000000,24222],[1453275300000,24284],[1453275600000,24331],...]
Array_2
[[1453274700000,51951],[1453275000000,52093],[1453275300000,52251],[1453275600000,52288],...]
Wanted_array
[[1453274700000,24011,51951],[1453275000000,24222,52093],[1453275300000,24284,52251],[1453275600000,24331,52288]...]
A functional solution:
$result = array_map(function (array $a1, array $a2) {
return array_merge($a1, [$a2[1]]);
}, $array_1, $array_2);
This assumes that all items are in order and only need to be merged by their order, not by their first value.
If you want $item[0] to define what "group" each value belongs to, you can iterate through the first array and save $item[0] as the key and $item[1] as the value. Do the same for the second array. Now iterate through the saved array for array1, and check if the saved array for array2 contains the same keys. Do the same for array2 (in case it has key that array1 doesn't have), and save it all to a new array:
<?php
$arr1 = array(
array('1453274700000',24011),
array('1453275000000',24222),
array('1453276000000',24222), // inexistent in $arr2
);
$arr2 = array(
array('1453275000000',52093),
array('1453274700000',51951),
array('1453273000000',24222), // inexistent in $arr1
);
$arr1dictionary = [];
$arr2dictionary = [];
$result = [];
foreach ($arr1 as $collection) {
$arr1dictionary[$collection[0]] = $collection[1];
}
foreach ($arr2 as $collection) {
$arr2dictionary[$collection[0]] = $collection[1];
}
foreach ($arr1dictionary as $key => $value) {
if (isset($arr2dictionary[$key])) {
$result[$key] = [$key, $value, $arr2dictionary[$key]];
} else {
$result[$key] = [$key, $value, null];
}
}
foreach ($arr2dictionary as $key => $value) {
if (isset($result[$key])) {
continue;
}
$result[$key] = [$key, null, $value];
}
$result = array_values($result);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453276000000
[1] => 24222
[2] => (null, the value only exists in $arr1)
)
[3] => Array
(
[0] => 1453273000000
[1] => (null, the value only exists in $arr2)
[2] => 24222
)
)
DEMO
Use array_walk and add second item from $array2 if it exists.
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331)
);
$array2 = array(
array(1453274700000,51951),
array(1453275000000,52093),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
if(isset($array2[$key][1])){
$item[] = $array2[$key][1];
}
});
print_r($array1);
Output
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
)
EDIT
As #h2ooooooo pointed out that there could be possibility that array items are in random order. If array items can be in random order and they are matched with first index value, use this (works with PHP >= 5.5.0):
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331),
array(1453276000000,24222) // no match in $array2
);
$array2 = array(
array(1453275000000,52093),
array(1453274700000,51951),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
// Find match in $array2
$array2_key = array_search($item[0], array_column($array2, 0));
// If match found
if($array2_key !== false && isset($array2[$array2_key][1])){
$item[] = $array2[$array2_key][1];
}
// No match
else{
$item[] = null;
}
});
print_r($array1);
OUTPUT
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
[4] => Array
(
[0] => 1453276000000
[1] => 24222
[2] =>
)
)

How to sorting multi array by value data?

how to sorting multi array by value ?
i have data like this
$num_a = $_POST['num_a']; //get the value data by array num_a[]
$num_b = $_POST['num_b']; //get the value data by array num_b[]
$score = $_POST['score']; //get the value data by array socre[]
for ($i=0; $i < count($num_a); $i++) {
//set total data num_a and num_b with value from score
$ring[($num_a[$i])][($num_b[$i])] = $score[$i];
}
print_r($ring);
//output
Array
(
[0] => Array
(
[1] => 5
)
[1] => Array
(
[2] => 1
)
[2] => Array
(
[0] => 3
)
)
how to display the results sorted by desc, so the results are like this, thank you
the output i want
print_r($ring);
Array
(
[0] => Array
(
[1] => 5
)
[2] => Array
(
[0] => 3
)
[1] => Array
(
[2] => 1
)
)
Try this
$data = [
0 => [ 1 => 5],
1 => [ 2 => 1],
2 => [ 0 => 3],
];
uasort($data, function($a, $b) {
$a = array_pop($a);
$b = array_pop($b);
if ($a == $b)
{
return 0;
}
return ($a < $b) ? 1 : -1;
});
var_dump($data);
You can also use array_multisort (PHP 4, PHP 5)
array_multisort(
array_map(function($_){return reset($_);},$ring),
SORT_DESC,
$ring
);
Test
[akshay#localhost tmp]$ cat test.php
<?php
$data = array(
array( 1 => 5),
array( 2 => 1),
array( 0 => 3),
);
// Input
print_r($data);
// Sort DESC
array_multisort(array_map(function($_){return reset($_);},$data), SORT_DESC, $data);
// Output - sorted array
print_r($data);
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[0] => Array
(
[1] => 5
)
[1] => Array
(
[2] => 1
)
[2] => Array
(
[0] => 3
)
)
Array
(
[0] => Array
(
[1] => 5
)
[1] => Array
(
[0] => 3
)
[2] => Array
(
[2] => 1
)
)

Combine arrays to form a multidimensional array

I have three arrays:
$arr1 = Array (
[0] => 1001
[1] => 1007
[2] => 1006);
$arr2 = Array (
[0] => frank
[1] => youi
[2] => nashua);
$arr3 = Array (
[0] => getfrankemail
[1] => getyouiemail
[2] => getnashuaemail);
Is there a way to combine these arrays to get a multidimensional array like this:?
Array (
[0] => Array (
[0] => 1001
[1] => frank
[2] => getfrankemail)
[1] => Array (
[0] => 1007
[1] => youi
[2] => getyouiemail)
[2] => Array (
[0] => 1006
[1] => nashua
[2] => getnashuaemail)
);
edit: what you are really looking for is a php version of the zip method in ruby/python.
For your specific example array_map works nicely:
$result = array_map(null, $arr1, $arr2, $arr3);
Output:
array (
0 =>
array (
0 => 1001,
1 => 'frank',
2 => 'frankemail',
),
1 =>
array (
0 => 1007,
1 => 'youi',
2 => 'youiemail',
),
2 =>
array (
0 => 1006,
1 => 'nashua',
2 => 'nashuaemail',
),
)
Iterate on the first array (looks like those are ids), and you can match the key for each value to indexes in $arr2 and $arr3
$result = array();
foreach ($arr1 as $key => $value) {
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
as #kingkero mentions in his answer, you will get errors if they keys do not exist, which you could check for and ignore any rows where that is the case.
$result = array();
foreach ($arr1 as $key => $value) {
if (!isset($arr2[$key]) || !isset($arr3[$key])) {
continue;
}
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
You could use array_push($aContainer, $arr1); or $aContainer[] = $arr[1]
You can do this with a loop in which you access each of the three arrays with the same key.
$result = array();
$max = count($arr1);
for ($i=0; $i<$max; $i++) {
$result[] = array(
$arr1[$i],
$arr2[$i],
$arr3[$i],
);
}
This could fire an out of bounds exception, since it doesn't check whether or not $arrX[$i] exists. Can you be sure that it does?

PHP: combining same-length arrays into a multidimensional array where both end up as values (not keys)?

I have two same-length arrays like this:
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
And I want to end up with this:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 3
)
)
array_combine would make one set of the above values into array keys, which I don't want -- I want both to end up as array values, combining each item of the two arrays into a new array.
Is there a built in function to do this or do I have to roll my own?
Try this:
$result = array();
foreach ($array1 as $i => $val) {
$result[] = array($val, $array2[$i]);
}
http://codepad.viper-7.com/Jx5H1Q
Is there a built in function to do this
Yes
or do I have to roll my own?
No
By calling array_map() and feeding it null as the callback parameter, then feeding it 2 or more arrays, it will restructure your data as desired.
Code: (Demo)
$array1 = ['a', 'b', 'c'];
$array2 = [1, 2, 3];
var_export(array_map(null, $array1, $array2));
Output:
array (
0 =>
array (
0 => 'a',
1 => 1,
),
1 =>
array (
0 => 'b',
1 => 2,
),
2 =>
array (
0 => 'c',
1 => 3,
),
)
If you had string keys, you could use array_merge_recursive to merge them. As it is, though, you'll need to do something else. For instance:
$result = Array();
$arrays = Array($array1,$array2...);
foreach($arrays as $arr) {
foreach($arr as $k=>$v) $result[$k][] = $v;
}

Categories