开发者

Undefined offset with count()

开发者 https://www.devze.com 2023-02-05 07:29 出处:网络
I have an array $MyArray which has some elements which are also array (lets call them subarrays). I want to know how many elements the subarray with the most elements has. The problem is, that I don\'

I have an array $MyArray which has some elements which are also array (lets call them subarrays). I want to know how many elements the subarray with the most elements has. The problem is, that I don't know if the index exists:

 max(
     @count($MyArray[$i*7]), 
     @count($MyArray[$i*7+1]), 
     @count($MyArray[$i*7+2]),         
     @count($MyArray[$i*7+3]),
     @count($MyArray[$i*7+4]),
     @count($MyArray[$i*7+5]),
     @count($MyArray[$i*7+6])
 );

Struckture of $MyArray:

Array(
  12 => array ( 
        0 => array ( 0 => 0, 1 => 1, ), 
        1 => array ( 0 => 13, 1 => 1, ), 
        2 => array ( 0 => 15, 1 => 1, ), 
        3 => array ( 0 => 20, 1 => 1, ), 
        4 => array ( 0 => 69, 1 => 1, ) 
  ),
  5 => array ( 
        0 => array ( 0 => 55, 1 => 1, ), 
        1 => array ( 0 => 32, 1 => 1, ), 
        2 =&g开发者_StackOverflow社区t; array ( 0 => 12, 1 => 1, ), 
        3 => array ( 0 => 21, 1 => 5, ) 
  ),
  ....
)

Can this be done better (faster)?

edit: I know foreach and I don't want to loop over every element in this array. I just want an interval of it. @ is used, because I don't know if $MyArray[$i*7 + x] is Null or an array.

$i is a element of [0, 1, 2, 3, 4] (sometimes also 5)


$biggest = 0;
foreach ($MyArray as $value) {
    if ($biggest < count($value)) {
        $biggest = count($value);
    }
}

I see, you want the size of the biggest array in the array, correct?


Simple and old school approach:

<?php

$max = -1;
foreach($MyArray as $subarray)
{
    $items = count($subarray);
    if($items > $max)
         $max = $items;
}

echo $max;
?>

This works best since you only want to know how many elements the subarray with the most elements has.


$max = 0;
foreach ($MyArray as $value) {
    $max = max($max,count($value));
}


Try this:

$arr = array();
for ($j=0;$j<=6;$j++) {
   if (isset($MyArray[$i*7+$j])) $arr[] = count($MyArray[$i*7+$j]);
}
$result = max($arr);

I don't know exactly what $i refers to though...


// get the interesting part of the array
$chunk = array_intersect_key($input_array, array_flip(range($i*7, $i*7+6))); 
// max(count)
$max = $chunk ? max(array_map('count', $chunk)) : 0;
0

精彩评论

暂无评论...
验证码 换一张
取 消