I have a basic function that takes two arrays and merges them based on key. It is meant to work with arrays that have different keys but ultimately the same number of items. The function works well. However, it only inputs two arrays at a time to merge.
How can I modify so it takes n number of arrays to merge?
PHP
protected function arrayMergeKeys( $a, $b )
{
$retArr = array();
// I used min(countA, countB) so there will be no errors on
// unbalanced array item counts.
for ( $i = 0; $i < min( count( $a ), count( $b ) ); $i++ ) {
$retArr[ $i ] = array_merge( $a[ $i ], $b[ $i ] );
} // for end
return $retArr;
}
Desired result is to call the function with three arrays: $merged_arrays = arrayMergeKeys($a, $b, $c);
Input
//$a
Array
(
[a] => 'new value'
[b] => 2
[c] => 3
)
//$b
Array
(
[1] => 'blah'
[2] => 'dud'
[3] => 697
)
//$c
Array
(
[pet] => 'dog'
[breed] => 'german shepher'
[age] => 100
)
Output
Array
{
[a] => 'new value'
[1] => 'blah'
[pet] => 'dog'
}
Array
{
[b] => 2
[2] => 'dud'
[breed] => 'german shepher'
}
Array
{
[c] => 3
[3] => 697
[age] => 100
}
Leaving your original function untouched you could do it like this:
function arrayMulitMergeKeys() {
$arrayArgs = func_get_args();
$c = count($arrayArgs);
$result = arrayArgs[0];
for($i = 1; $i < $c; $i++) {
$result = arrayMergeKeys($result, $arrayArgs[$i]);
}
return $result;
}
This can be optimized further please re-check it once again
function arrayMergeKeys()
{
$retArr = array();
$arrayArgs = func_get_args();
//print_r($arrayArgs);
$minCount = count($arrayArgs[0]);
foreach($arrayArgs as $array){
if($minCount > count($array)){
$minCount = count($array);
}
}
// I used min(countA, countB) so there will be no errors on
// unbalanced array item counts.
for ( $i = 0; $i < $minCount; $i++ ) {
foreach($arrayArgs as $array){
$iCount = count($array);
for($j=0; $j<=$iCount; $j++)
{
if($i==$j){
$arrayKeys = array_keys($array);
if(isset($arrayKeys[$i])){
$retArr[ $i ][$arrayKeys[$i]] = $array[$arrayKeys[$i]];
break;
}
}
}
}
} // for end
return $retArr;
}
$a = Array
(
'a' => 'new value',
'b' => 2,
'c' => 3
);
$b = array
(
'1' => 'blah',
'2' => 'dud',
'3' => 697
);
$c = array
(
'pet' => 'dog',
'breed' => 'german shepher',
'age' => 100
);
print_r(arrayMergeKeys($a, $b, $c));
Here's some pseudo code to point you in the right direction.
function mergeArrays(a, b, c)
arrays = []
shortestLength = min(a.len, b.len, c.len)
for i in [0 .. shortestLength - 1]
arrays[i] = [ a[i], b[i], c[i] ];
return arrays
If you're doing this as an exercise, I would suggest implementing the following also:
mergeArrays(arr) where arr is an array of arrays that need to be merged.
Haven't tested, but this should work
protected function arrayMergeKeys(...$arrs) {
$retArr = array();
// I used min(countA, countB) so there will be no errors on
// unbalanced array item counts.
$countArr = array();
foreach ($arrs as $arr) {
$countArr[] = count($arr);
}
$min = min($countArr);
for ( $i = 0; $i < $min; $i++ ) {
$mergeArr = array();
foreach ($arrs as $arr) {
$mergeArr[] = $arr[$i];
}
$retArr[ $i ] = array_merge( $mergeArr );
} // for end
return $retArr;
}
You can simply 'add' the arrays:
$a = array
(
'a' => 'new value',
'b' => '2',
'c' => '3'
);
//$b
$b = array
(
'1' => 'blah',
'2' => 'dud',
'3' => '697'
);
//$c
$c = array
(
'pet' => 'dog',
'breed' => 'german shepher',
'age' => 100
);
$result= $a+$b+$c;
print_r($result);
output
Array ( [a] => new value [b] => 2 [c] => 3 [1] => blah [2] => dud [3] => 697 [pet] => dog [breed] => german shepher [age] => 100 )
Related
I have multiple arrays like this:
array (
[floorBuildingName] => Array
(
[0] => Lt.1
[1] => Lt.2
)
[roomFloorName] => Array
(
[0] => Single
[1] => Medium1
[2] => MaXI
)
)
I would like to merge the two arrays into a single array.
For example:
array (
[0] => array(
[0] =>Lt.1,
[1] =>Single
),
[1] => array(
[0] =>Lt.2,
[1] =>Medium1
),
[2] => array(
[0] =>Lt.2,
[1] =>MaXI
)
)
How can I achieve this?
First, you have to determine the maximum array length. Then, create a new array and finally, put the elements at the given index into the new array. If the index is out of bounds, then use the last element.
var $maxNumber = 0;
foreach ($myArray as $array) {
$maxNumber = max($maxNumber, count($array));
}
$result = array();
for ($index = 0; $index < $maxNumber; $index++) {
$result[] = array();
foreach($myArray as $array) {
if (count($array) < $maxNumber) {
$result[$index][] = $array(count($array) - 1);
} else {
$result[$index][] = $array[$index];
}
}
}
Assuming that you want to pad out uneven arrays with the last value in the array:
$data = ['floorBuildingName' => [..], ..];
// find the longest inner array
$max = max(array_map('count', $data));
// pad all arrays to the longest length
$data = array_map(function ($array) use ($max) {
return array_pad($array, $max, end($array));
}, $data);
// merge them
$merged = array_map(null, $data['floorBuildingName'], $data['roomFloorName']);
You can do this using array_map very Easily:
Try this code:
$arr1 = array(1, 2);
$arr2 = array('one', 'two', 'three', 'four');
while(count($arr1) != count($arr2)) {
//If Array1 is Shorter then Array2
if (count($arr1)<count($arr2)) {
$arr1[] = $arr1[count($arr1) - 1];
}
//If Array2 is Shorter then Array1
if (count($arr1) > count($arr2)) {
$arr2[] = $arr2[count($arr2) - 1];
}
}
//Now merge arrays
$newarray = (array_map(null, $arr1, $arr2));
print_r($newarray);
Will Output:
Array
(
[0] => Array
(
[0] => 1
[1] => one
)
[1] => Array
(
[0] => 2
[1] => two
)
[2] => Array
(
[0] => 2
[1] => three
)
[3] => Array
(
[0] => 2
[1] => four
)
)
there's the solution for different number of arguments:
$floorBuildingName = array(
'Lt.1',
'Lt.2'
);
$roomFloorName = array(
'Single', 'Medium1', 'MaXI'
);
class ValueArrayIterator extends ArrayIterator
{
protected $arrays;
protected $latestValues = [];
public function __construct(array $mainArray) {
parent::__construct($mainArray);
$this->arrays = func_get_args();
}
public function current()
{
$returnValue = [];
foreach ($this->arrays as $arrayKey => $array) {
if (isset($array[$this->key()])) {
$this->latestValues[$arrayKey] = $array[$this->key()];
}
$returnValue[] = $this->latestValues[$arrayKey];
}
return $returnValue;
}
}
$iterator = new ValueArrayIterator($roomFloorName, $floorBuildingName);
$newArray = iterator_to_array($iterator);
Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.
I've got an array like this:
$a = array(
array(2 => 1, 4 => 2, 9 => 3),
array(3 => 7, 4 => 5, 7 => 3),
array(1 => 6, 4 => 5),
...
);
So the array contains a huge amount of sub arrays with integer key => integer value.
Now I want to find subarrays which share no keys or if they share a key the value of this key must be the same.
Example: $a[1] and $a[2] would match because $a[1][4] == $a[2][4] and no other keys match. But $a[0] and $a[1] would not match because $a[0][4] != $a[1][4].
The number of elements in the subarrays may vary.
Is there an efficient way to do this ? The only way I can think of is check each possible pair in a nested loop resulting in O(n^2).
If someone has an idea for a more meaningful title feel free to edit it.
Maybe code makes it more clear: (naive implementation)
$pairs = array();
for($i = 0; $i < count($a); $i++)
for($j = $i+1; $j < count($a); $j++)
if(array_intersect_key($a[$i], $a[$j]) == array_intersect_assoc($a[$i], $a[$j]))
$pairs[] = array($i, $j);
Alternative:
$matching = array();
for($i = 0; $i < count($a); $i++)
for($j = $i+1; $j < count($a); $j++)
if(array_intersect_key($a[$i], $a[$j]) == array_intersect_assoc($a[$i], $a[$j]))
list($matching[$i][], $matching[$j][]) = array($j, $i);
There might be ways to do it, but it somewhat depends on if you know how many matches are likely (or the general 'matchyness' of your data). If there's more matches than not it might be better to start with assuming everything matches and eliminating.
In any case, I think you can pre-process the data. I'm not sure if this is faster -- it really depends on the distribution of your data, but I'd start by trying something like this and work from there:
$a = array(
array(2 => 1, 4 => 2, 9 => 3),
array(3 => 7, 4 => 5, 7 => 3),
array(1 => 6, 4 => 5),
array(1 => 6, 4 => 5, 7 => 5),
array(2 => 1, 4 => 2, 9 => 3)
);
// 1 and 2 match, 2 and 3 match, 0 and 4 match
$keyData = array();
for ($i = 0; $i < count($a); $i++) {
foreach($a[$i] as $k => $v) {
if (!isset($keyData[$k])) {
$keyData[$k] = array();
}
if (!isset($keyData[$k][$v])) {
$keyData[$k][$v] = array();
}
$keyData[$k][$v][] = $i;
}
}
$potentialMatches = array();
foreach ($keyData as $key => $values) {
// Ignore single key/value pairs
if (count($values) > 1) {
foreach ($values as $value => $arrayIndices) {
for ($i = 0; $i < count($arrayIndices); $i ++) {
for ($j = $i + 1; $j < count($arrayIndices); $j ++) {
$potentialMatches[] = array($arrayIndices[$i], $arrayIndices[$j]);
}
}
}
}
}
// You might need to do this ...
/*
foreach ($potentialMatches as &$m) {
array_unique($m);
}
*/
$pairs = array();
foreach ($potentialMatches as $m) {
if(array_intersect_key($a[$m[0]], $a[$m[1]])
== array_intersect_assoc($a[$m[0]], $a[$m[1]])) {
$pairs[] = $m;
}
}
print_r($pairs);
Output:
Array
(
[0] => Array
(
[0] => 0
[1] => 4
)
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 2
[1] => 3
)
)
EDIT
As I said in my comment, that doesn't catch arrays that don't share any keys -- which you consider a match. The code below does this, although I'm not sure if it's faster than the nested solution (and it's going to use a ton of memory)
// New test data to cover the case I missed
$a = array(
array(2 => 1, 4 => 2, 9 => 3),
array(3 => 7, 4 => 5, 7 => 3),
array(1 => 6, 4 => 5),
array(1 => 6, 4 => 5, 7 => 5),
array(2 => 1, 4 => 2, 9 => 3),
array(8 => 3)
);
// 1 and 2 match, 2 and 3 match, 0 and 4 match, 5 matches all
// First assume everything is a match, build an array of:
// indicies => array of potential matches
$potentialMatches = array_fill(0, count($a), array_keys($a));
// Build data about each key, the indicies that contain that key
// and the indicies for each value of that key
$keyData = array();
for ($i = 0; $i < count($a); $i++) {
foreach($a[$i] as $k => $v) {
if (!isset($keyData[$k])) {
$keyData[$k] = array();
}
if (!isset($keyData[$k][$v])) {
$keyData[$k][$v] = array();
}
$keyData[$k]['all'][] = $i;
$keyData[$k][$v][] = $i;
}
}
// print_r($keyData);
// Now go through the key data and eliminate indicies that
// can't match
foreach ($keyData as $key => $values) {
if (count($values) > 2) { // Ignore single key/value pairs
// Two indecies do not match if they appear in seperate value lists
// First get the list of all indicies that have this key
$all = array_unique($values['all']);
unset($values['all']);
// Now go through the value lists
foreach ($values as $value => $arrayIndices) {
// The indicies for this value cannot match the other
// indices in the system, i.e. this list
$cantMatch = array_diff($all, $arrayIndices);
// So remove the indicies that can't match from the potentials list
foreach ($arrayIndices as $index) {
$potentialMatches[$index] = array_diff($potentialMatches[$index], $cantMatch);
}
}
}
}
//print_r($potentialMatches);
// You said you didn't mind the output format, so that's probably enough
// but that array contains (x,x) which is pointless and both (x,y) and (y,x)
// so we can do one final bit of processing to print it out in a nicer way
$pairs = array();
foreach ($potentialMatches as $x => $matches) {
foreach ($matches as $y) {
if ( ($x < $y) ) {
$pairs[] = array($x, $y);
}
}
}
print_r($pairs);
Output
Array
(
[0] => Array
(
[0] => 0
[1] => 4
)
[1] => Array
(
[0] => 0
[1] => 5
)
[2] => Array
(
[0] => 1
[1] => 2
)
[3] => Array
(
[0] => 1
[1] => 5
)
[4] => Array
(
[0] => 2
[1] => 3
)
[5] => Array
(
[0] => 2
[1] => 5
)
[6] => Array
(
[0] => 3
[1] => 5
)
[7] => Array
(
[0] => 4
[1] => 5
)
)
if you are looking for adjacent matching,
$temp = null;
$last_result = array();
foreach($a as $key => $value){
if(is_null($temp)){
$temp = $value;
} else{
$result = array_intersect_assoc($temp, $value);
if(!empty($result))
array_push($last_result, $result);
$temp = $value;
}
}
print_r($last_result);
otherwise just use array_intersect_assoc
for a example you can do like this
$res = array_intersect_assoc($a[0],$a[1],$a[2]);
print_r($res);
This is an interesting situation which I created a working function for, but wondering if I just anyone had any simpler methods for this.
I have the following multidimensional array:
$foo = array(
[0] => array(
'keys' => array(
'key1' => 1,
'key2' => a,
'key3' => 123
),
'values' => array(
//goodies in here
)
)
[1] => array(
'keys' => array(
'key1' => 1,
'key2' => b,
'key3' => 456
),
'values' => array(
//goodies in here
)
)
)
What I wanted, was to transform this into a multidimensional array nested based on the values from the keys array, the output I was looking for is:
$bar = array(
[1] => array(
[a] => array(
[123] => array( //values array from above )
),
[b] => array(
[456] => array( //values array from above )
)
)
)
The keys can always be nested based on their position in the keys array, but the keys themselve are not always the same, keys handles a user defined grouping, so the order and values can change. I also didn't want duplicate keys.
array_merge failed me because in a lot of cases, the array keys are actually numeric ids. So, this function works - but I'm wondering if I made myself a new pair of gloves.
protected function convertAssociativeToMulti( &$output, $keys, $value )
{
$temp = array();
$v = array_values( $keys );
$s = sizeof( $v );
for( $x = 0; $x < $s; $x++ )
{
$k = $v[ $x ];
if ( $x == 0 )
{
if ( !array_key_exists( $k, $output ) )
$output[ $k ] = array();
$temp =& $output[ $k ];
}
if ( $x && ( $x + 1 ) !== $s )
{
if( !array_key_exists( $k, $temp ) )
$temp[ $k ] = array();
$temp =& $temp[$k];
}
if ( ( $x + 1 ) == $s )
$temp[$k] = $value;
}
}
$baz = array();
foreach( $foo as $bar )
{
$this->convertAssociativeToMulti( $baz, $bar['keys'], $bar['values'] );
}
So, how do you do this more simply / refactor what I have?
This is a bit more concise (See it in action here):
$bar=array();
foreach($foo as $item)
{
$out=&$bar;
foreach($item['keys'] as $key)
{
if(!isset($out[$key])) $out[$key]=array();
$out=&$out[$key];
}
foreach($item['values'] as $k=>$v) $out[$k]=$v;
// $out=array_merge($out,$item['values']); -- edit - fixed array_merge
}
var_dump($bar);
It should quite simple algorithm, but I just can't get around it.
I have some arrays in alphabetical order
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
and for example
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
and I need to sort them into rows. For example:
I should receive a table with 3 columns and as many rows as it may get and it should be in alphabetical order.
Here is an example:
First array should be converted into
[0] => Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
But second one should be as
[1] => Array
(
[0] => Array
(
[0] => a
[1] => c
[2] => d
)
[1] => Array
(
[0] => b
)
)
I'm writing it in php, so if anyone can help I would be really appreciated.
UPD:
Code example:
function sortAsOrdered( array $categories )
{
foreach ( $categories as $groupId => $group )
{
$regroupMenuItems = array();
$limit = count( $group );
$rows = ceil( $limit / 3 );
for ( $i = 0; $i < $rows; ++$i )
{
$jumper = 0;
for ( $j = 0; $j < 3; $j++ )
{
if ( 0 == $jumper )
{
$jumper = $i;
}
if ( isset( $group[ $jumper ] ) )
{
$regroupMenuItems[ $i ][ $j ] = $group[ $jumper ];
}
$jumper = $jumper + $rows;
}
}
$categories[ $groupId ] = $regroupMenuItems;
}
return $categories;
}
Guys I solved this one. Here you could see my algorithm http://pastebin.com/xe2yjhYW.
But don't be sad your help will not go in vain. I probably will place bounty just for those who helped with this dificult algorithm for me.
Guys thanks one more time. Your thoughts inspired me to think differently.
array_chunk() wold have been the solution but as you want it to be specially sorted, that wouldn't help you much.
So here is my five cents:
function array_chunk_vertical($input, $size_max) {
$chunks = array();
$chunk_count = ceil(count($input) / $size_max);
$chunk_index = 0;
foreach ($input as $key => $value) {
$chunks[$chunk_index][$key] = $value;
if (++$chunk_index == $chunk_count) {
$chunk_index = 0;
}
}
return $chunks;
}
$array = array('a', 'b', 'c', 'd', 'e', 'f');
var_dump(array_chunk_vertical($array, 2));
Which will give you:
array
0 =>
array
0 => string 'a' (length=1)
3 => string 'd' (length=1)
1 =>
array
1 => string 'b' (length=1)
4 => string 'e' (length=1)
2 =>
array
2 => string 'c' (length=1)
5 => string 'f' (length=1)
The downside of this function is that you can only tell the max number of elements in a chunk, and then it equally divides the array to chunks. So for [4] and max_size 3 you will get [2,2] unlike the expected [3,1].
<?php
$five_el = array('a', 'b', 'c', 'd', 'e');
$two_el = array('a', 'b');
$three_el = array('a', 'b', 'c');
$six_el = array('a', 'b', 'c', 'd', 'e', 'f');
function multid($sorted_array) {
$mulidarray = array();
$row = 0;
$column = 0;
foreach ($sorted_array as $value) {
if ($column == 3) {
$row++;
}
$column++;
if (!isset($mulidarray[$row])) {
$mulidarray[$row] = array();
}
$multidarray[$row][] = $value;
}
return $multidarray;
}
var_dump(multid($five_el));
var_dump(multid($two_el));
var_dump(multid($three_el));
var_dump(multid($six_el));
array_chunk is a natural first approach to the problem, but it won't do exactly what you need to. If the solution is provided that way, you need to either restructure the resulting array or restructure the input before processing it, as below:
$input = range('a', 'k'); // arbitrary
$columns = 3; // configure this
$rows = ceil(count($input) / $columns);
// fugly, but this way it works without declaring a function
// and also in PHP < 5.3 (on 5.3 you'd use a lambda instead)
$order = create_function('$i',
'$row = (int)($i / '.$rows.');'.
'$col = $i % '.$rows.';'.
'return $col * ('.$columns.' + 1) + $row;');
// $order is designed to get the index of an item in the original array,
// and produce the index that item would have if the items appeared in
// column-major order instead of row-major as they appear now
$array = array_map($order, array_keys($input));
// replace the old keys with the new ones
$array = array_combine($array, $input);
// sort based on the new keys; this will effectively transpose the matrix,
// if it were already structured as a matrix instead of a single-dimensional array
ksort($array);
// done!
$array = array_chunk($array, $columns);
print_r($array);
See it in action.
Let's see if this is nearer the mark
function splitVerticalArrayIntoColumns($aInput, $iNumberOfColumns) {
//output array
$aOutput = array();
//the total length of the input array
$iInputLength = count($aInput);
//the number of rows will be ceil($iInputLength / $iNumberOfColumns)
$iNumRows = ceil($iInputLength / $iNumberOfColumns);
for($iInputIndex = 0; $iInputIndex < $iInputLength; $iInputIndex++) {
$iCurrentRow = $iInputIndex % $iNumRows;
$aOutput[$iCurrentRow][] = $aInput[$iInputIndex];
}
//return
return $aOutput;
}
Which - when run thus:
$aList = array("a", "e", "d", "b", "c");
echo 'array("a", "e", "d", "b", "c")' . "\n\n";
print_r(splitVerticalArrayIntoColumns($aList, 3));
Gives:
array("a", "e", "d", "b", "c")
Array
(
[0] => Array
(
[0] => a
[1] => d
[2] => c
)
[1] => Array
(
[0] => e
[1] => b
)
)
That's not sorting each row yet but is that the kind of thing you're after?
begin facepalm edit
... or of course, array_chunk($aList, 3) after you've sorted it O_o
http://uk3.php.net/manual/en/function.array-chunk.php
I'll leave everything below for reference or whatever - I'd completely forgotten about array_chunk()
end facepalm edit
I'd use a modulo in a loop where you're counting the array index (after sorting the array) - for instance if you're trying to split an array into 3 "columns" you could try something like:
if($iIndex % 3 == 0) {
//... create a new array
}
else {
//... add to an existing array
}
EDIT code example:
$aList = array("a", "e", "d", "b", "c");
sort($aList);
$iDesiredNumberOfColumns = 3;
$iListLength = count($aList);
$aListInColumns = array();
$iRowNumber = 0;
for($iIndex = 0; $iIndex < $iListLength; $iIndex++) {
$iColumnNumber = $iIndex % 3;
if($iIndex != 0 && $iColumnNumber == 0) {
$iRowNumber++;
}
$aListInColumns[$iRowNumber][$iColumnNumber] = $aList[$iIndex];
}
Just ran it on my local server (and corrected the typo), and it outputs as:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
[1] => Array
(
[0] => d
[1] => e
)
)
There's probably a tidier way of doing it (that's a little procedural) but it should do the job.
How about:
$arrs = array(
array('a','b','c'),
array('a','b','c','d'),
array('a','b','c','d','e'),
array('a','b','c','d','e','f'),
array('a','b','c','d','e','f','g')
);
$nbcols = 3;
foreach ($arrs as $arr) {
$arr_size = count($arr);
$nblines = ceil($arr_size/$nbcols);
$res = array();
$l = 0;
foreach ($arr as $el) {
if ($l == $arr_size - 1 && count($res[0]) < $nbcols) $l=0;
$res[$l%$nblines][] = $el;
$l++;
}
print_r($res);
}
output:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
Array
(
[0] => Array
(
[0] => a
[1] => c
[2] => d
)
[1] => Array
(
[0] => b
)
)
Array
(
[0] => Array
(
[0] => a
[1] => c
[2] => e
)
[1] => Array
(
[0] => b
[1] => d
)
)
Array
(
[0] => Array
(
[0] => a
[1] => c
[2] => e
)
[1] => Array
(
[0] => b
[1] => d
[2] => f
)
)
Array
(
[0] => Array
(
[0] => a
[1] => d
[2] => g
)
[1] => Array
(
[0] => b
[1] => e
)
[2] => Array
(
[0] => c
[1] => f
)
)
In order to do this, you need to do two operations:
First, split the array into 3 groups, as evenly as possible.
function array_grouped($arr, $group_count)
{
if (!count($arr)) return array();
$result = array();
for ($i = $group_count; $i > 0; --$i)
{
# break off the next ceil(remaining count / remaining columns) elements
# (avoiding FP math, cause that way lies madness)
$result[] = array_splice($arr, 0, ((count($arr)-1) / $i) + 1);
}
return $result;
}
Then, "transpose" the array, so that rows and columns switch places.
function array_transposed($arr)
{
$result = array();
foreach ($arr as $x => $subarr)
{
foreach ($subarr as $y => $val)
{
if (!isset($result[$y])) $result[$y] = array();
$result[$y][$x] = $val;
}
}
return $result;
}
array_transposed(array_grouped($arr, 3)) gives you entries in the order you want them.
YAYAYAY!! I've got it. You could turn this into a function if you'll be doing it regularly.
# Here we setup our array and the number of columns we want.
$myArray = range('a','d');
$numCols = 3;
# Here we break ourselves up into columns
for ($i = 0; $i < $numCols; $i++) {
$numRows = ceil(count($myArray) / ($numCols - $i));
$columns[$i] = array_slice($myArray,0,$numRows);
$myArray = array_slice($myArray,$numRows);
}
# Here we transpose our array to be in rows instead of columns.
for ($i = 0; $i < $numCols; $i++) {
for ($j = 0; $j < count($columns[$i]); $j++) {
$rows[$j][$i] = $columns[$i][$j];
}
}
# Our rows are now in $rows
var_dump($rows);
The output from this is:
array(2) {
[0]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "c"
[2]=>
string(1) "d"
}
[1]=>
array(1) {
[0]=>
string(1) "b"
}
}
If to say it shortly, then here is a method for that algorithm.
/**
* #param array $toTransform
* #param int $columnsMax
* #return array
*/
private function transformation( array $toTransform, $columnsMax = 3 )
{
// First divide array as you need
$listlen = count( $toTransform );
$partlen = floor( $listlen / $columnsMax );
$partrem = $listlen % $columnsMax;
$partition = array();
$mark = 0;
for ( $px = 0; $px < $columnsMax; $px++ )
{
$incr = ( $px < $partrem ) ? $partlen + 1 : $partlen;
$partition[ $px ] = array_slice( $toTransform, $mark, $incr );
$mark += $incr;
}
// Secondly fill empty slots for easy template use
$result = array();
for ( $i = 0; $i < count( $partition[0] ); $i++ )
{
$tmp = array();
foreach ( $partition as $column )
{
if ( isset( $column[ $i ] ) )
{
$tmp[] = $column[ $i ];
}
else
{
$tmp[] = '';
}
}
$result[] = $tmp;
}
return $result;
}
Also I included PHPUnit test for that. You can find it at, that link.