Merge every other array php - php

array one: 1,3,5,7
array two: 2,4,6,8
the array i want would be 1,2,3,4,5,6,7,8
I'm just using numbers as examples. If it was just numbers i could merge and sort but they will be words. So maybe something like
array one: bob,a,awesome
array two: is,really,dude
should read: bob is a really awesome dude
Not really sure how to do this. Does PHP have something like this built in?

You could write yourself a function like this:
function array_merge_alternating($array1, $array2) {
if(count($array1) != count($array2)) {
return false; // Arrays must be the same length
}
$mergedArray = array();
while(count($array1) > 0) {
$mergedArray[] = array_shift($array1);
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}
This function expects two arrays with equal length and merges their values.
If you don't need your values in alternating order you can use array_merge. array_merge will append the second array to the first and will not do what you ask.

Try this elegant solution
function array_alternate($array1, $array2)
{
$result = Array();
array_map(function($item1, $item2) use (&$result)
{
$result[] = $item1;
$result[] = $item2;
}, $array1, $array2);
return $result;
}

This solution works AND it doesn't matter if both arrays are different sizes/lengths:
function array_merge_alternating($array1, $array2)
{
$mergedArray = array();
while( count($array1) > 0 || count($array2) > 0 )
{
if ( count($array1) > 0 )
$mergedArray[] = array_shift($array1);
if ( count($array2) > 0 )
$mergedArray[] = array_shift($array2);
}
return $mergedArray;
}

Try this function:
function arrayMergeX()
{
$arrays = func_get_args();
$arrayCount = count($arrays);
if ( $arrayCount < 0 )
throw new ErrorException('No arguments passed!');
$resArr = array();
$maxLength = count($arrays[0]);
for ( $i=0; $i<$maxLength; $i+=($arrayCount-1) )
{
for ($j=0; $j<$arrayCount; $j++)
{
$resArr[] = $arrays[$j][$i];
}
}
return $resArr;
}
var_dump( arrayMergeX(array(1,3,5,7), array(2,4,6,8)) );
var_dump( arrayMergeX(array('You', 'very'), array('are', 'intelligent.')) );
var_dump( arrayMergeX() );
It works with variable numbers of arrays!
Live on codepad.org: http://codepad.org/c6ZuldEO

if arrays contains numeric values only, you can use merge and sort the array.
<?php
$a = array(1,3,5,7);
$b = array(2,4,6,8);
$merged_array = array_merge($a,$b);
sort($merged,SORT_ASC);
?>
else use this solution.
<?php
function my_merge($array1,$array2)
{
$newarray = array();
foreach($array1 as $key => $val)
{
$newarray[] = $val;
if(count($array2) > 0)
$newarray[] = array_shift($array2)
}
return $newarray;
}
?>
hope this help

Expects both arrays to have the same length:
$result = array();
foreach ($array1 as $i => $elem) {
array_push($result, $elem, $array2[$i]);
}
echo join(' ', $result);

Related

Array comparison and re-order in PHP

Let's say I Have two arrays.
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
now compare two arrays.if there is no match for value of $arr1 in $arr2 then index is left empty.
for the above arrays output should be:
$arr3 = ['','','C','D']
I tried array_search() function.But couldn't achieve desired output.
Any possible solutions?
You can use foreach with in_array and array_push like:
$arr1 = ['A','B','C','D'];
$arr2 = ['C','D'];
$arr3 = [];
foreach($arr1 as $value){
$arr3[] = (in_array($value, $arr2)) ? $value : '';
}
print_r($arr3);
/*
Result
Array
(
[0] =>
[1] =>
[2] => C
[3] => D
) */
Foreach the first array then test with in_array if exist, if true push into array 3 else push empty value
You can use the following function. In the following code, the function search_in_array return true and false based on the searching within the 2nd array. So you can push the empty or searched value in final array.
<?php
$arr1 = array('A','B','C','D');
$arr2 = array('C','D');
$arr3 = array();
function search_in_array ($value, $array)
{
for ($i=0; $i<count($array); $i++)
{
if ($value == $array[$i])
{
return true;
}
}
return false;
}
for ($i=0; $i<count($arr1); $i++)
{
$value = $arr1[$i];
$result = search_in_array ($value, $arr2);
if ($result)
{
array_push ($arr3, $value);
}
else
{
array_push ($arr3, '');
}
}
print_array($arr3);
?>

re-arrange multidimensional php array

I need to re-arrange a php multidimensional array so that to 'match' corresponding values from different arrays;
this is my reproducible example
<?php
// my original array
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4)
);
print_r($myar);
// my desired result, new array
$myar_new= array(
array('xxx'=>1,'yyy'=>2),
array('xxx'=>3,'yyy'=>4)
);
print_r($myar_new);
?>
any help for that?
thanks
If I got your logic right then this function is what you need.
(Edited)
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
$i = 0;
$groupStart = null;
$collect = [];
while($i < $c) {
$row = current($srcArray[$i]);
if ($row == $groupStart) {
$newArray[] = $collect;
$collect = [];
}
$tmp = array_values($srcArray[$i]);
$collect[] = [$tmp[0] => $tmp[1]];
if ($groupStart === null) $groupStart = $row;
$i++;
}
$newArray[] = $collect;
return $newArray;
}
print_r(strange_reformat($myar));
yes, that's it...
but now I need to generalise it, please consider this case
$myar= array(
array('A'=>'xxx','B'=>1),
array('A'=>'yyy','B'=>2),
array('A'=>'zzz','B'=>5),
array('A'=>'xxx','B'=>3),
array('A'=>'yyy','B'=>4),
array('A'=>'zzz','B'=>6)
);
function strange_reformat($srcArray) {
$newArray = [];
$c = count($srcArray);
for ($i=0; $i<$c; $i+=3) {
$first = array_values($srcArray[$i]);
$second = array_values($srcArray[$i+1]);
$third = array_values($srcArray[$i+2]);
$newArray[] = [$first[0]=>$first[1], $second[0]=>$second[1], $third[0]=>$third[1]];
}
return $newArray;
}
print_r(strange_reformat($myar));

How to recursively combine array in php

I want to combine two arrays into a dictionary.
The keys will be the distinct values of the first array, the values will be all values from the second array, at matching index positions of the key.
<?php
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
?>
array_combine($b,$a);
Expected result as
<?php
/*
Value '1' occurs at index 0, 1 and 4 in $b
Those indices map to values 2, 3 and 6 in $a
*/
$result=[1=>[2,3,6],3=>4,2=>[5,7],6=>8,8=>[9,10]];
?>
There are quite a few PHP array functions. I'm not aware of one that solves your specific problem. you might be able to use some combination of built in php array functions but it might take you a while to weed through your choices and put them together in the correct way. I would just write my own function.
Something like this:
function myCustomArrayFormatter($array1, $array2) {
$result = array();
$num_occurrences = array_count_values($array1);
foreach ($array1 AS $key => $var) {
if ($num_occurrences[$var] > 1) {
$result[$var][] = $array2[$key];
} else {
$result[$var] = $array2[$key];
}
}
return $result;
}
hope that helps.
$a=[2,3,4,5,6,7,8,9,10];
$b=[1,1,3,2,1,2,6,8,8];
$results = array();
for ($x = 0; $x < count($b); $x++) {
$index = $b[$x];
if(array_key_exists ($index, $results)){
$temp = $results[$index];
}else{
$temp = array();
}
$temp[] = $a[$x];
$results[$index] = $temp;
}
print_r($results);
Here's one way to do this:
$res = [];
foreach ($b as $b_index => $b_val) {
if (!empty($res[$b_val])) {
if (is_array($res[$b_val])) {
$res[$b_val][] = $a[$b_index];
} else {
$res[$b_val] = [$res[$b_val], $a[$b_index]];
}
} else {
$res[$b_val] = $a[$b_index];
}
}
var_dump($res);
UPDATE: another way to do this:
$val_to_index = array_combine($a, $b);
$result = [];
foreach ($val_to_index as $value => $index) {
if(empty($result[$index])){
$result[$index] = $value;
} else if(is_array($result[$index])){
$result[$index][] = $value;
} else {
$result[$index] = [$result[$index], $value];
}
}
var_dump($result);

Sort php Array by integers inside values

I'm trying to sort an array numerically but the integers are found in the middle of a value, not on the first character. Here is what my array looks like (using dummy values):
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
sort($array,1);
Output after foreach:
A25
A30
A40
AB25
AB30
AB40
B25
B30
B40
Expected output:
A25
AB25
B25
A30
AB30
B30
A40
AB40
B40
What would be the best sorting method for this? Really appreciate it, thanks!
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
usort(
$array,
function($a, $b) {
list($achar,$anum) = sscanf($a, '%[A-Z]%d');
list($bchar,$bnum) = sscanf($b, '%[A-Z]%d');
if ($anum > $bnum) {
return 1;
} elseif (($anum == $bnum) && ($achar > $bchar)) {
return 1;
}
return -1;
}
);
var_dump($array);
Have created a custom function depending on your requirement, please see below code
<?php
$array = array('A30','A25','ZZZ','A40','Rohan','B25','B30','Sakhale','B40','AB25','AB30','AB40');
$array = sortArrayByNumber($array);
var_dump($array);
/**
* #name sortArrayByNumber
* #abstract sort the entire array irrespective of the string, but the numbers into it
* also we append the elements not having any number at the end
* #author Rohan Sakhale
*/
function sortArrayByNumber($arr){
$sortedArr = array();
$tempArray = array();
$stringOnlyArray = array();
foreach($arr as $v){
$num = getNumberFromString($v);
/**
* If no number found, append it into stringOnlyArray
*/
if($num == ''){
$stringOnlyArray[] = $v;
continue;
}
if(!isset($tempArray[$num])){
$tempArray[$num] = array();
}
$tempArray[$num][] = $v;
}
$tempArrayKeys = array_keys($tempArray);
sort($tempArrayKeys);
foreach($tempArrayKeys as $key){
sort($tempArray[$key]);
$sortedArr = array_merge($sortedArr, $tempArray[$key]);
}
if(count($stringOnlyArray) > 0){
sort($stringOnlyArray);
$sortedArr = array_merge($sortedArr, $stringOnlyArray);
}
return $sortedArr;
}
/**
* #str - String param which tend to have number
*/
function getNumberFromString($str){
$matches = null;
preg_match_all('!\d+!', $str, $matches);
if(!is_null($matches) and is_array($matches)){
if(isset($matches[0][0])){
return $matches[0][0];
}
}
return '';
}
?>
Here sort by number method is trying to firstly identify the number's in your string and maintain a separate array of it based on the keys, later we sort in ascending order every key's of number and then we finally merge it into sorted array
You can use user defined function with usort to achieve it
<?php
function mySort($a,$b) {
$numA = '';
$strA = '';
$numB = '';
$strB = '';
for($i=0;$i<strlen($a); $i++) {
if(is_numeric($a[$i])) {
$numA .= (string)$a[$i];
}
else {
$strA .= $a[$i];
}
}
for($i=0;$i<strlen($b); $i++) {
if(is_numeric($b[$i])) {
$numB .= (string)$b[$i];
}
else {
$strB .= $b[$i];
}
}
$numA = (int)$numA;
$numB = (int)$numB;
if($numA>$numB) {
return true;
}
elseif($numA<$numB) {
return false;
}
else {
if(strcmp($strA,$strB)>0) {
return true;
}
else {
return false;
}
}
}
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
var_dump($array);
usort($array,'mySort');
var_dump($array);
?>
Here's a stable sort, the result is: "A25" "B25" "AB25" "A30" "B30" "AB30" "A40" "B40" "AB40" .
function getNum($str)
{
preg_match ( '/(\d+)$/', $str, $match );
return intval ( $match [1] );
}
function stableSort($arr)
{
$newArr = array ();
foreach ( $arr as $idx => $ele )
{
$newArr [] = array (
'idx' => $idx,
'val' => $ele
);
}
usort ( $newArr,
function ($a, $b)
{
$d = getNum ( $a ['val'] ) - getNum ( $b ['val'] );
return $d ? $d : $a ['idx'] - $b ['idx'];
} );
$sortArr = array ();
foreach ( $newArr as $ele )
{
$sortArr [] = $ele ['val'];
}
return $sortArr;
}
var_dump ( stableSort ( $array ) );
U can use various kinds of ways to sort arrays in PHP. PHP has some good ways build in to do sorting on arrays. In this case I agree with Mark Baker, however I would recommend a preg_replace to get the numeric value of your strings.
$array = Array('A25','A30','A40','B25','B30','B40','AB25','AB30','AB40');
function cmp($a, $b)
{
$v1 = preg_replace("/[^0-9]/", "", $a);
$v2 = preg_replace("/[^0-9]/", "", $b);
if ($v1 == $v2) {
return 0;
}
return ($v1 < $v2) ? -1 : 1;
}
usort($array, "cmp");
var_dump($array);
Look into the PHP information about sorting arrays, php.net/usort and various others.

How to get the duplicate keys of multiple arrays?

I know about array_intersect_key which returns duplicate keys of the first parameter in any of the following parameters.
However I was wondering which would be the easiest way to find duplicate keys across more than two arrays at once? Does PHP offer such a function or do I need to do it with multiple calls?
Given
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
Duplicate keys across all three arrays are moin and tag.
I thought so far about calling array_intersect_keys on each possible pair of parameters (in a function accepting a 2-n number of arrays as parameters) but have problems to actually find all possible combinations. And perhaps there is a much more easier way to do this.
Here's a custom function I made which does what you're looking for:
function array_duplicate_keys()
{
$keys = array();
foreach(func_get_args() as $arr)
{
if(!is_array($arr))
{
continue;
}
foreach($arr as $key => $v)
{
if(!isset($keys[$key]))
{
$keys[$key] = -1;
}
$keys[$key]++;
}
}
return array_keys(array_filter($keys));
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
/*
print_r(array_duplicate_keys($a1, $a2, $a3));
Array
(
[0] => tag
[1] => moin
)
*/
I think your idea is good - call it on every possible combination of arrays. Two nested for loops should be enough to get all combinations:
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
$all = array($a1, $a2, $a3);
function pair_duplicate_keys($arrays) {
$keys = array();
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (!isset($keys[$key])) {
$keys[$key] = 1;
} else {
$result[$key] = 1;
}
}
}
return array_keys($result);
}
print_r(pair_duplicate_keys($all));
Output
Array
(
[0] => moin
[1] => tag
)
All you need is a simple call to array_merge function:
$a = array_merge($a1, $a2, $a3);
print_r($a);
OUTPUT
Array
(
[hello] => 1
[tag] => 1
[moin] => 1
)
Ugly, but does the job:
function array_duplicate_keys() {
return array_keys(array_filter(array_count_values(call_user_func_array('array_merge', array_map('array_keys', func_get_args()))), function ($num) {
return $num > 1;
}));
}
$a1 = array('hello'=>1, 'tag'=>1);
$a2 = array('moin'=>1);
$a3 = array('moin'=>1, 'tag'=>1);
print_r(
array_duplicate_keys($a1, $a2, $a3)
);
Output:
Array
(
[0] => tag
[1] => moin
)

Categories