Petter Adam
Petter Adam

Reputation: 57

How to change rows with columns in matrix with same width?

Values in my matrix is

1 2 3

4 5 6

7 8 9

10 11 12

13 14 15

I want to put second columns as rows starting with from column 2 as (the same width and length of matrix)

Like that

2 5 8

11 14 1

4 7 10

13 3 6

9 12 15

I use that function I know its return the same matrix with no changes

function change($matrix){
$new_matrix =array();
foreach ($matrix as $row => $values) {
foreach ($values as $columns=>$value) {
    $new_matrix[$row][$columns] = $value;
}   
}
return $new_matrix;
}

I can use that function but it very bad structure

function change1($matrix)
{
$list= array(
        array($matrix[0][1],$matrix[1][1],$matrix[2][1]),
        array($matrix[3][1],$matrix[4][1],$matrix[0][0]),
        array($matrix[1][0],$matrix[2][0],$matrix[3][0] ),
        array($matrix[4][0],$matrix[0][2],$matrix[1][2] ),
        array($matrix[2][2],$matrix[3][2],$matrix[4][2] ),
);
return $list;

}

Upvotes: 0

Views: 511

Answers (2)

Mark Baker
Mark Baker

Reputation: 212452

$data = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9),
    array(10, 11, 12),
    array(13, 14, 15),
);

array_unshift($data, null);
$newData = call_user_func_array('array_map', $data);
$newData = array_chunk(
    array_merge_recursive($newData[1], $newData[0], $newData[2]),
    3
);
var_dump($newData);

Upvotes: 1

MH2K9
MH2K9

Reputation: 12039

If you have PHP 5.5+ can simply use array_column(). Then merge all columns in linear array. Example:

$arr1 = array_column($arr, 1);
$arr2 = array_column($arr, 0);
$result = array_merge($arr1, $arr2);
$arr1 = array_column($arr, 2);
$result = array_chunk(array_merge($result, $arr1), 3);
foreach($result as $val){
    foreach($val as $v){
        echo $v . ' ';
    }
    echo '<br />';
}

Upvotes: 0

Related Questions