Search code examples
phpmultidimensional-arrayrotationorientation

Rotate an array of arrays clockwise 90 degrees


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?


Solution

  • 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);