Joining Arrays in PHP [duplicate] - php

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 10 months ago.
This is really simple but I need a quick way to do this.
I have three arrays like
$a = array('a','b','c');
$p = array('p','q','r');
$x = array('x','y','z');
How do I combine them to make
array (
[0] => array ('a','p','x');
[1] => array ('b','q','y');
[2] => array ('c','r','z');
);

Wouldn't array_map(null, $a, $p, $x); be better?
See array_mapĀ­Docs.

<?php
$a = array('a','b','c');
$p = array('p','q','r');
$x = array('x','y','z');
$arr = array();
for($i=0; $i<count($a); $i++){
$arr[$i] = array($a[$i], $p[$i], $x[$i]);
}
?>

array_map is simpler, but for the sake of possibibility, a quickly typed code example to make use of the MultipleIterator to solve the issue:
$it = new MultipleIterator;
foreach(array($a, $p, $x) as $array) {
$it->attachIterator(new ArrayIterator($array));
}
$items = iterator_to_array($it, FALSE);
Might be handy in case it's more than an array.

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;
}
}

Combine PHP array as something [duplicate]

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;
}

php array of arrays to 1D array not getting properly as expected

I am reading value from CMD which is running a python program and my output as follows:
Let as assume those values as $A:
$A = [[1][2][3][4]....]
I want to make an array from that as:
$A = [1,2,3,4....]
I had tried as follows:
$val = str_replace("[","",$A);
$val = str_replace("]","",$val);
print_r($val);
I am getting output as:
Array ( [0] => 1 2 3 4 ... )
Please guide me
try this
// your code goes here
$array = array(
array("1"),
array("2"),
array("3"),
array("4")
);
$outputArray = array();
foreach($array as $key => $value)
{
$outputArray[] = $value[0];
}
print_r($outputArray);
Also check the example here https://ideone.com/qaxhGZ
This will work
array_reduce($a, 'array_merge', array());
Multidimensional array to single dimensional array,
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($A));
$A = iterator_to_array($it, false);
But, if $A is string
$A = '[[1][2][3][4]]';
$A = explode('][', $A);
$A = array_map(function($val){
return trim($val,'[]');
}, $A);
Both codes will get,
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
This function will work when you do indeed have a multidimensional array, which you stated you have, in stead of the String representation of a multidimensional array, which you seem to have.
function TwoDToOneDArray($TwoDArray) {
$result = array();
foreach ($TwoDArray as $value) {
array_push($result, $value[0]);
}
return $result;
}
var_dump(TwoDToOneDArray([[0],[1]]));
You can transform $A = [[1],[2],[3],[4]] into $B = [1,2,3,4....] using this following one line solution:
$B = array_map('array_shift', $A);
PD: You could not handle an array of arrays ( a matrix ) the way you did. That way is only for managing strings. And your notation was wrong. An array of arrays (a matrix) is declared with commas.
If you have a string like you wrote in the first place you can try with regex:
$a = '[[1][2][3][4]]';
preg_match_all('/\[([0-9\.]*)\]/', $a, $matches);
$a = $matches[1];
var_dump($a);
If $A is a string that looks like an array, here's one way to get it:
$A = '[[1][2][3][4]]';
print "[".str_replace(array("[","]"),array("",","),substr($A,2,strlen($A)-4))."]";
It removes [ and replaces ] with ,. I just removed the end and start brackets before the replacement and added both of them after it finishes. This outputs: [1,2,3,4] as you can see in this link.

How can you sort each element inside of an array alphabetically [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 8 years ago.
For example we have the following words: hey, hello, wrong
$unsorted = array("eyh", "lhleo", "nrwgo");
I know that I could use asort to sort the array alphabetically, but I don't want that.
I wish to take the elements of the array and sort those, so that it would become something like this:
$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted
hey sorted = ehy
hello sorted = ehllo
wrong sorted = gnorw
As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.
Thanks in advance!
function sort_each($arr) {
foreach ($arr as &$string) {
$stringParts = str_split($string);
sort($stringParts);
$string = implode('', $stringParts);
}
return $arr;
}
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
$myArray,
function (&$value) {
$value = str_split($value);
sort($value);
$value = implode($value);
}
);
print_r($myArray);
Try this
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString = implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);

need to map two arrays to one array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php values of one array to key of another array
I have the sorted array
$A = array(
0=>EUR,
1=>GBP,
2=>USD
);
$B = array(
0=>'0.88',
1=>'0'
);
I want to map to be like this allways put 'EUR'=>'1':
$C = array(
'EUR'=>'1',
'GBP'=>'0.88',
'USD'=>'0'
);
Could anyone tell me please?
$C = array_combine($A, array_merge(array(1), $B));
$C = array();
foreach ($A as $key => $value)
{
$C[$value] = $B[$key];
}

Categories