0

I would like to rotate the orientation of an array so that rows and columns are inverted.

For example, I want to convert this:

1     cat     calico
2     dog     collie
3     cat     siamese
4     dog     mutt

to this:

4       3        2         1
dog     cat      dog       cat
mutt    siamese  collie    calico

How can I accomplish this?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Ralph M. Rivera
  • 769
  • 3
  • 12
  • 25
  • 2
    Sounds like you want to transpose a multidimensional array: http://stackoverflow.com/questions/797251/transposing-multidimensional-arrays-in-php –  Mar 12 '12 at 20:50
  • Can you show us some of your code please. – Oyeme Mar 12 '12 at 20:50
  • 1
    I'm not sure what you're asking here, are you trying to display the information in a different way on the page? If so, this is not a PHP question, but rather an HTML/CSS question. – Keith Frey Mar 12 '12 at 20:51

2 Answers2

1

Here is a way you can accomplish this:

function rotate_2d_array($array)
{
    $result = array();
    foreach (array_values($array) as $key => $sub_array)
    {
        foreach (array_values($sub_array) as $sub_key => $value)
        {
            if (empty($result[$sub_key]))
            {
                $result[$sub_key] = array($value);
            }
            else
            {
                array_unshift($result[$sub_key], $value);
            }
        }
    }
    return $result;
}

And here is the test:

$a = array(
    array(1, 'cat','calico'),
    array(2, 'dog', 'collie'),
    array(3, 'cat', 'siamese'),
    array(4, 'dog', 'mutt')
);
print_r($a);

$b = rotate_2d_array($a);
print_r($b);
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
0
$initialData = array( 1 => array('cat', 'calico'),
                      2 => array('dog', 'collie'),
                      3 => array('cat', 'siamese'),
                      4 => array('dog', 'mutt'),
                    );

$transposedArray = call_user_func_array('array_map',array_merge(array(NULL),$initialData));

var_dump($transposedArray);

Note that it loses the array indexing though, and is simply a one-line variant of @Codler's response in the question linked by @Keith

Mark Baker
  • 209,507
  • 32
  • 346
  • 385
  • This answer is not well explained. Asking the OP and researchers to "trust our magic" doesn't empower them -- it makes them more dependent upon us to do their work for them. – mickmackusa Aug 30 '21 at 07:02
  • This answer is performing "transposition", not clockwise rotation. This answer is incorrect. Incorrect result: https://3v4l.org/2q1Fk – mickmackusa Apr 23 '22 at 07:43