views:

489

answers:

2

Normally I'd be asking how to turn something like this:

1      2        3
4      5        6
7      8        9
10    11       12

Into this:

1   4   7   10
2   5   8   11
3   6   9   12

But actually I want to turn it into this:

1   5   9
2   6   10
3   7   11
4   8   12

In other words, I want to flip the rows and columns, but keep the same "width" and "height" of the new array. I've been stuck on this for over an hour.

This is the function I'm using to do a normal "flip" (the first example):

function flip($arr)
{
    $out = array();

    foreach ($arr as $key => $subarr)
    {
            foreach ($subarr as $subkey => $subvalue)
            {
                 $out[$subkey][$key] = $subvalue;
            }
    }

    return $out;
}
+4  A: 

Just walk the array in the correct order. Assuming you have relatively small arrays, the easiest solution is just to create a brand new array during that walk.

A solution will be of the form:

$rows = count($arr);
$cols = count($arr[0]); // assumes non empty matrix
$ridx = 0;
$cidx = 0;

$out = array();

foreach($arr as $rowidx => $row){
    foreach($row as $colidx => $val){
        $out[$ridx][$cidx] = $val;
        $ridx++;
        if($ridx >= $rows){
            $cidx++;
            $ridx = 0;
        }
    }
}
Mark E
Excellent, this works perfectly.
Gnuffo1
A: 

here you go. It works. :)



$input1 = array(1,2,3);
$input2 = array(4,5,6);
$input3 = array(7,8,9);
$input4 = array(10,11,12);

$input = array($input1,$input2,$input3,$input4);

echo "\n input array";print_r($input);

// flipping matrices
$output = array();
$intern = array();

for($row=0; $row lt 4; $row++)
    for($col=0;$col lt 3;$col++)
        $intern[] = $input[$row][$col];

echo "\n intern ";print_r($intern);

// nesting the array
$count = 0;
$subcount = 0;

foreach($intern as $value)
{

    $output[$count][$subcount] = $value;
    $count++;

    if($subcount == 3)
    {
        break;
    }

    if($count == 4)
    {
        $count = 0;
        $subcount++;
    }


}


echo "\n final output ";print_r($output);