在php中,二维数组中的行数和列数


In php, Number of rows and columns in a 2 D array?

我有一个元素数量未知的二维数组。

$two_darray[row][column]; //there will be an unknown integer values instead of row and column keywords

如果我要按如下方式编写一个for循环,我如何确定我的$two_darray中有多少行和列。你能告诉我php中是否有一个库函数可以告诉我[????][???]内的值吗

for($row=0; $row<………; $row++)
{
    for($column =0; $column  <………; $ column ++)
    {
        echo $two_darray[$row][$column];
    }
    echo “'n end of one column 'n”;
}

我真的需要知道行和列的值,以便执行其他计算。

foreach ($two_darray as $key => $row) {
   foreach ($row as $key2 => $val) {
      ...
   }
}

无需担心每个数组中有多少元素,因为foreach()会为您处理它。如果您绝对拒绝使用foreach,那么在出现每个数组时只使用count()

$rows = count($two_d_array);
for ($row = 0; $row < $rows; $row++) {
     $cols = count($two_darray[$row]);
     for($col = 0; $col < $cols; $col++ ) {
        ...
     }
}

我就是这么做的:我的超级英雄阵列:

$superArray[0][0] = "DeadPool";
$superArray[1][0] = "Spiderman";
$superArray[1][1] = "Ironman";
$superArray[1][2] = "Wolverine";
$superArray[1][3] = "Batman";

获取大小:

echo count( $superArray ); // Print out Number of rows = 2
echo count( $superArray[0] ); // Print Number of columns in $superArray[0] = 1
echo count( $superArray[1] ); // Print Number of columns in $superArray[1] = 4

php

对于php多维数组,请使用

$rowSize = count( $arrayName );
$columnSize = max( array_map('count', $arrayName) );

如果需要知道实际数字,则可以使用sizeof()count()函数来确定每个数组元素的大小。

$rows = count($two_darray) // This will get you the number of rows
foreach ($two_darray as $row => $column)
{
    $cols = count($row);
}

普通、非混合二维阵列、的快速方法

$Rows=计数($array);$colomns=(count($array,1)-count($array))/count($array);

对于php索引的二维数组:

$arName = array(
  array(10,11,12,13),
  array(20,21,22,23),
  array(30,31,32,33)
);
$col_size=count($arName[$index=0]);
for($row=0; $row<count($arName); $row++)
{
  for($col=0; $col<$col_size; $col++)
  {
    echo $arName[$row][$col]. " ";
  }
  echo "<br>";
}

输出:

10 11 12 13
20 21 22 23
30 31 32 33