Create transpose matrix with php

For example, if the matrix:

1 2 3 4 5 6 

Then the transposition of the above matrix will be:

 1 3 5 2 4 6 

This is my current code:

 <?php // transpose matrix $trans = array( array(1, 2), array(3, 4), array(5, 6) ); foreach ($trans as $key => $val){ foreach ($trans[$key] as $k => $v){ echo $v; } } ?> 
+5
source share
1 answer

There's a fancy PHP way to transpose a 2d array:

 $trans = array( array(1, 2), array(3, 4), array(5, 6) ); array_unshift($trans, null); $trans = call_user_func_array('array_map', $trans); var_dump($trans); 

Demo

EDIT A Simple Approach Using PHP 5.6 Unpacking Arrays

With the introduction of the function to unpack array arguments in PHP 5.6, we can simplify this even further:

 $trans = array( array(1, 2), array(3, 4), array(5, 6) ); $trans = array_map(null, ...$trans); var_dump($trans); 

EDIT Explanation

Quote from the PHP docs for the array_map () function:

An interesting use of this function is to create an array of arrays that can be easily done using NULL as the name of the callback function

(see example # 4 on this documentation page for an example of what this does)

array_unshift($trans, null) that we execute first provides a NULL callback, and we use call_user_func_array() because we don’t necessarily know how many values ​​there are in our $trans array. What we do with call_user_func_array() is equivalent to:

 $trans = array_map(NULL, $trans[0], $trans[1], $trans[2]); 

for your array of examples, because the top level of your 2-dimensional array has three elements (keys 0, 1, and 2).

Effectively, this NULL callback goes through all arrays in parallel, taking each of them from the queue to build a new array:

 $maxArraySize = max(count($array[0], $array[1], $array[2]); // $maxArraySize will have a value of 2 in your case, // because your sub-arrays are all equal size $newArray = []; for($i = 0; $i < $maxArraySize; ++$i) { $tmpArray = []; $tmpArray[] = $array[0][$i]; $tmpArray[] = $array[1][$i]; $tmpArray[] = $array[2][$i]; $newArray[] = $tmpArray[]; } 

There are a couple of additional checks

  • it doesn't matter if your arrays are associative or listed in any dimension because it accesses the element $i th, not the index
  • If the sub-arrays do not have the same length, then it efficiently pushes shorter sub-arrays with zero values ​​according to the length of the longest
  • It doesn't matter how many arrays you go through, it will work with them all in parallel.
+15
source

Source: https://habr.com/ru/post/986692/


All Articles