PHP的 - 如何翻转的2D阵列的行和列 [英] PHP - how to flip the rows and columns of a 2D array

查看:157
本文介绍了PHP的 - 如何翻转的2D阵列的行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常我会问如何把这样的事情:

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

进入这个:

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

但事实上我想让它变成这样:

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

在换句话说,我想翻转的行和列,但保持相同的宽度和新的数组的高度。我一直停留在这一个多小时。

这是我使用的是做一个正常的翻转功能(第一个例子):

 翻转功能($ ARR)
{
    $ OUT =阵列();    的foreach($改编为$关键=> $ subarr)
    {
            的foreach($ subarr为$子项= GT; $子值)
            {
                 从$ [$子] [$关键] = $子值;
            }
    }    返回$出;
}


解决方案

只是走在了正确的顺序排列。假设你有比较小的阵列,最简单的方法就是在那段步行到创建一个全新的数组。

一个解决方案将是下面的形式:

  $行=计数($ ARR);
$ COLS =计数($改编[0]); //假设非空矩阵
$ ridx = 0;
$ CIDX = 0;$ OUT =阵列();的foreach($改编为$ rowidx => $行){
    的foreach($行为$ colidx => $ VAL){
        从$ [$ ridx] [$ CIDX] = $ VAL;
        $ ridx ++;
        如果($ ridx> = $行){
            $ CIDX ++;
            $ ridx = 0;
        }
    }
}

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;
}

解决方案

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;
        }
    }
}

这篇关于PHP的 - 如何翻转的2D阵列的行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆