PHP Array.length 二维数组(y 轴)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5237640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:43:01  来源:igfitidea点击:

PHP Array.length for a two dimensional array (y axis)

phpmultidimensional-array

提问by Spencer

I am trying to use a function whereby I see how tall (y axis) a two dimensional array is in PHP. How would you suggest that I do this? Sorry, I am new to PHP.

我正在尝试使用一个函数,通过它我可以看到一个二维数组在 PHP 中的高度(y 轴)。你会如何建议我这样做?抱歉,我是 PHP 新手。

回答by phihag

max(array_map('count', $array2d))

回答by Jacob Mattison

A multi-dimensional array is simply an array of arrays -- it's not like you've blocked out a rectangular set of addresses; more like a train where each car can be stacked as high as you like.

多维数组只是一个数组数组——它不像你已经屏蔽了一组矩形地址;更像是一列火车,每节车厢都可以堆到你喜欢的高度。

As such, the "height" of the array, presumably, is the count of the currently largest array member. @phihag has given a great way to get that (max(array_map(count, $array2d))) but I just want to be sure you understand what it means. The max height of the various arrays within the parent array has no effect on the size or capacity of any given array member.

因此,数组的“高度”大概是当前最大数组成员的计数。@phihag 提供了一个很好的方法来获得(max(array_map(count, $array2d))),但我只是想确保您理解它的含义。父数组中各种数组的最大高度对任何给定数组成员的大小或容量没有影响。

回答by Naftali aka Neal

$max = 0;

foreach($array as $val){
 $max = (count($val)>$max?count($val):$max)
}

where $max is the count you are looking for

其中 $max 是您要查找的计数

回答by mario

If the y-axis is the outer array, then really just count($array). The second dimension would just be count($array[0])if it's uniform.

如果 y 轴是外部数组,那么实际上只是count($array). 第二个维度只是count($array[0])如果它是统一的。

回答by Adam Hopkinson

To sum up the second dimension, use countin a loop:

总结第二个维度,count在循环中使用:

$counter = 0;
foreach($var AS $value) {
    $counter += count($value);
}

echo $counter;

回答by Czechnology

1.dimension:

1.维度:

count($arr);

2.dimension:

2.维度:

function count2($arr) {
  $dim = 0;

  foreach ($arr as $v) {
    if (count($v) > $dim)
      $dim = count($v);
  }

  return $dim;
}

As it is possible to have each array / vector of different length (unlike a mathematical matrix) you have to look for the max. length.

由于每个数组/向量的长度可能不同(与数学矩阵不同),因此您必须寻找最大值。长度。

回答by Kersh

In my application I have used this approach.

在我的应用程序中,我使用了这种方法。

$array = array();

$array[0][0] = "one";
$array[0][1] = "two";

$array[1][0] = "three";
$array[1][1] = "four";

for ($i=0; isset($array[$i][1]); $i++) {
    echo $array[$i][1];
}

output: twofour

输出:twofour

Probably, this is not the best approach for your application, but for mine it worked perfectly.

可能这不是您的应用程序的最佳方法,但对于我的应用程序来说,它工作得很好。