且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中将一维数组转换为二维数组?

更新时间:2022-06-05 05:25:37

我认为您应该使用array_chunk();

I think you should use array_chunk();

$stack = array(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8);

$split = 4;

$array = array_chunk($stack, $split);

print_r($array);

会输出:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [1] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 7
            [3] => 8
        )

    [2] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )

    [3] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 7
            [3] => 8
        )

)

已更新
如果您的目标是将数组转换为矩阵,则可以采用以下解决方案。该解决方案还可以将矩阵显示为矩阵。

UPDATED If your goal is to convert an array to a matrix then here is a solution. The solution also has a way to display the matrix as a matrix.

 function arrayToMat($array, $split){

  if(count($array) % $split == 0){

    $row = 1;

    for($i = 0; $i < count($array); $i += $split){

      for($j = 0; $j < $split; $j++){

        $mat[$row][$j+1] = $array[$i+$j];

      }

    $row++;

    }

    return $mat;

  } else {

  return FALSE;

  }

}



function displayMat($mat){

  echo
  '<table>';

  for($i = 1; $i <= count($mat); $i++){

    echo
    '<tr>';

    for($j = 1; $j <= count($mat[$i]); $j++){

      echo
      '<td>' .
      $mat[$i][$j] .
      '</td>';

    }

    echo
    '</tr>';

  }

  echo
  '</table>' . '<br><br>';

}




$stack = array(1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8);

$split = 4;

$mat = arrayToMat($stack, $split); //Will output your desired matrix indexes starting at 1;
//Will return false if cannot form a matrix.

//Show array structure.  Indexes start at 1;
print_r($mat);

//Prints out as matrix.
displayMat($mat);

//Change up the splits.
$mat = arrayToMat($stack, 2); //8x2 
displayMat($mat);

$mat = arrayToMat($stack, 4); //4x4
displayMat($mat);

$mat = arrayToMat($stack, 6); //Returns False

$mat = arrayToMat($stack, 8); //2x8
displayMat($mat); 

这将输出:

//Indexes start at 1.
Array
(
    [1] => Array
        (
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

    [2] => Array
        (
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
        )

    [3] => Array
        (
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
        )

    [4] => Array
        (
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
        )

)

1   2   3   4
5   6   7   8
1   2   3   4
5   6   7   8

//8x2
1   2
3   4
5   6
7   8
1   2
3   4
5   6
7   8

//4x4  
1   2   3   4
5   6   7   8
1   2   3   4
5   6   7   8

//False with a split of 6

//2x8
1   2   3   4   5   6   7   8
1   2   3   4   5   6   7   8