为了账号安全,请及时绑定邮箱和手机立即绑定

基于行数的数据透视数组

基于行数的数据透视数组

PHP
繁华开满天机 2023-04-21 13:34:55
我有以下内容:$array = array(1,2,3,4,5,6);我需要“旋转”它以获得:Array ( [0] => 1 [1] => 4 [2] => 2 [3] => 5 [4] => 3 [5] => 6 )我所说的“枢轴”是指,让我们假设该数组存储了一个 2 x 3 矩阵(2 行和 3 列)。我的目标是旋转它,使矩阵现在是一个 3 x 2 矩阵(3 行,2 列)为此,我当然需要一个额外的参数,比方说“行数”(在这种情况下,这就像 2 行)我做了以下事情:function pivotArray($array, $nbrRows){  $countTotal = count($array);  $countCols = $countTotal / $nbrRows;  $chunk = array_chunk($array,$countCols);  $out = array();  for ($row=0;$row<$nbrRows;$row++) {    for ($col=0;$col<$countCols;$col++) {    $out[$col][$row] = $chunk[$row][$col];    }  }  $arraySingle = call_user_func_array('array_merge', $out);  return $arraySingle;    }它按设计工作,但我想知道是否有更好的方法来做到这一点?例如避免 2 for 循环?并避免 array_merge ?
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

这段代码没有对数组进行多次处理,而是构建了一个中间数组并基于 展开元素$position % $countCols。我还介绍了ceil()列数,以防元素数量为奇数......


function pivotArray($array, $nbrRows)

{

    $countTotal = count($array);

    $countCols = ceil($countTotal / $nbrRows);

    $arraySingle = [];

    foreach ( $array as $position => $value )   {

        $arraySingle[$position % $countCols][] = $value;

    }


    return array_merge(...$arraySingle);

}


查看完整回答
反对 回复 2023-04-21
  • 1 回答
  • 0 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信