Combine PHP array as something [duplicate] - php

This question already has answers here:
Combining php arrays
(3 answers)
Closed 7 years ago.
I have two arrays:
$arr1= array("A","B","C");
$arr2= array("1","2","3");
Output i need as:
$arr3= array("A","1","B","2","C","3");
Can anyone help please?

If your first two arrays has the same length, you can use a loop to get the array you want:
<?PHP
$arr1= array("A","B","C");
$arr2= array("1","2","3");
$arr3=[];
for($i = 0; $i < count($arr1); $i++)
array_push($arr3, $arr1[$i], $arr2[$i]);
?>
It will return:
$arr3= array("A","1","B","2","C","3");

Take a look at array_merge()
array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values
of one are appended to the end of the previous one. It returns the
resulting array.
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one. If, however, the arrays
contain numeric keys, the later value will not overwrite the original
value, but will be appended.

This will work to combine the two arrays together:
$output = $array1 + $array2;

This snippet could solve what you asked, also if arrays are not equal in length.
function array_interpolation($arr1, $arr2) {
$result = array();
$len1 = count($arr1);
$len2 = count($arr2);
$maxlen = max($len1, $len2);
for($i = 0; $i < $maxlen; $i++) {
if($i < $len1) {
array_push($result, $arr1[$i]);
}
if($i < $len2) {
array_push($result, $arr2[$i]);
}
}
return $result;
}

Related

How to merge multiple arrays in PHP but mix values together - retaining their order [duplicate]

This question already has answers here:
Transpose and flatten two-dimensional indexed array where rows may not be of equal length
(4 answers)
Closed 5 months ago.
Is there a straightforward way in PHP to combine multiple arrays together but respect the relative order of the elements?
So for example if I had two arrays
$x = ('1','2','3','4');
and
$y = array('a','b','c','d','e');
and I wanted combine them into a single array
$z = ('1','a','2','b','3','c','4','d','e');
Is there a straightforward way of doing this? The ideal solution would also account for different lengths of arrays, behaving as my example does.
array_merge doesn't seem to achieve what I want as it just appends one array to the other.
My current solution loops through each array in order and pushes values to my $z array. This is not only inelegant, it also requires the input arrays to have the same number of values, which isn't ideal for my application.
Any insight would be appreciated
I think this should work -
$count = max(count($x), count($y));
$newArr = array();
for ($i = 0; $i < $count; $i++) {
// enter values to the new array based on key
foreach(array($x, $y) as $arr) {
if (isset($arr[$i])) {
$newArr[] = $arr[$i];
}
}
}
var_dump($newArr);
You could use this generic function, which can accept any number of arrays, and will output an array with the elements taken from the first "column" first, then from the second, etc:
function mix_merge(...$args) {
return call_user_func_array('array_merge',
array_map(function($i) use ($args) { return array_column($args, $i); },
range(0, max(array_map('count', $args))-1)));
}
// Sample data:
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
$z = array('A','B','C');
$res = mix_merge($x, $y, $z);
Result array will be:
['1', 'a', 'A', '2', 'b', 'B', '3', 'c', 'C', '4', 'd', 'e']
Iterate from 0 to the greater length of the two arrays.
At each step, if array $x contains item at index, push it to final array $z. Do the same for array $y.
You can also try this
$x = array('1','2','3','4');
$y = array('a','b','c','d','e');
foreach($y as $key=>$value){
if($x[$key]){
$z[] = $x[$key];
$z[] = $value;
}else {
$z[] = $value;
}
}

Merge array values, alternating [duplicate]

This question already has answers here:
Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion
(2 answers)
Closed last year.
I'm trying to merge arrays but would like to alternate the order.
$combined = array_merge($vars,$mods);
gives me: one,two,three,1,2,3...
I'd like: one,1,two,2,three,3...
is there a way to do this?
You can use a for loop and refer to the index of each of the arrays you're combining.
$l = count($vars);
for ($i=0; $i < $l; $i++) {
$combined[] = $vars[$i];
$combined[] = $mods[$i];
}
In each iteration of the loop, you'll append one item from each of the original arrays. This will achieve the alternating effect.
As Steve pointed out, this can be done more simply using foreach:
foreach ($vars as $i => $value) {
$combined[] = $value;
$combined[] = $mods[$i];
}

Combine two assosiative array's if (id) value are the same

So I got two associative arrays containing key-value pairs. They share one key name, and I want to add one array to the other if the "name" values are equal.
So if you have these arrays:
$array1 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(some other key-value pairs)];
$array2 = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(some other key-value pairs)];
the result should be something like this:
$newArray = [name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
(the other key-value pairs from $array1),
app=>array(
name=>"Foo",
date=>array("2016-06-06", "2016-06-05", "2016-06-04"),
download_count=>array(54,23,15),
(the other key-value pairs from $array2))]
Right now I try to loop through both of the array's to see where the names of both array's at index $i,$j are the same, and if they are combine the two.
Here is the code I use for that
foreach($array1 as $foo){
foreach($array2 as $bar){
if($foo["name"] == $bar["name"]){
$foo["app"] = $bar;
}
}
}
alternatively I tried with just regular for loops like this:
for($i = 0; $i < count($array1); $i++){
for($j = 0; $j < count($array2); $i++){
if($array1[$i]["name"] == $array2[$j]["name"]){
$array1[$i]["app"] = $array2[$j];
break;
}
}
}
The result from the first example is just $array1 (unchanged), and the result form the alternative example is an infinite loop.
Could someone help figure out how to get the desirable result?
Edit
Got it working, was just a beginners error in this case both for loops increased $i by one instead of the first loop adding one to $i and the other adding ine to $j

PHP specific merge array

I have 2 arrays
$arr1 = array(1,3);
$arr2 = array(2,4);
I want merge them to one array with structure:
$arr = array(1,2,3,4);
Has php functions for that or exist good solution?
UPD: i don't need sort values, i want put elements from first array to odd positions, elements from second to even positions
You would have to merge them first, then sort them:
$arr = array_merge($arr1, $arr2);
sort($arr);
There is no built-in function to do what you are describing, assuming they are both the same length:
$len = count($arr1);
for($x=0; $x < $len; $x++) {
array_push($arr, $arr1[$x], $arr2[$x]);
}
$new_arr = array_merge($arr1, $arr2)
No. Php does not have a function for this that I know of. You'll have to write your own, but it's very simple.
Pseudocode:
cmb = []
for (i=0, i<arr1.length, i++) {
array_push(cmb, arr1[i]);
array_push(cmb, arr2[i]);
}

Combine and transpose multiple single-dimensional arrays into a single multi-dimensional array

I have three single-dimensional arrays and I need to combine them into one 3-dimensional array where each array in the new array contains one element of each of the three original arrays.
I know how to do this using a simple loop but I was wondering if there is a faster / built-in way of doing this. here is an example of doing this with a loop so you can understand what I'm looking for.
function combineArrays(array $array1, array $array2, array $array3) {
//Make sure arrays are of the same size
if(count($array1) != count($array2) || count($array2) != count($array3) || count($array1) != count($array3)) {
throw new Exception("combineArrays expects all paramters to be arrays of the same length");
}
//combine the arrays
$newArray = array();
for($count = 0; $count < count($array1); $count++) {
$newArray[] = array($array1[$count], $array2[$count], $array3[$count]);
}
return $newArray;
}
$result = array_map(null,$array1,$array2,$array3);

Categories