0

このスクリプトは、多次元配列を取得し、値を反復処理することになっています。

配列のサイズは 10 で、各要素には連想配列が含まれている必要があります。

$games[0] => array('foo' => 'bar')
$games[1] => array('foo1' => 'bar1')
etc..

この例では、while ループは 5 回反復する必要があります。for ループは、while ループの反復ごとに 10 回反復する必要があります。

だから私はエコーが次のようになることを期待しています:

countwhile = 5 countfor = 50 totalgames = 50

しかし、私は実際に得ています

countwhile = 5 countfor = 150 totalgames = 150

$games 配列は問題ではないと思います。以前に以下でその呼び出しを行い、print_r を使用してコンテンツを表示したことがあり、期待どおりであるためです。

このコード全体は、私の index.php ページにあるように、関数またはクラスに含まれていません。変数のスコープに問題があるのでしょうか?

$totalruns = 5;  
$endindx = 10;
$startindx = 0;
$countwhile = 0;
$countfor = 0;
$totalfilesize = 0;
$totalgames = 0; 
$sizeof = 0; 

while($totalruns > 0)  
{  
     $games = $feedHandler->getGames($startindx, $endindx);  
     $sizeof = sizeof($games);  

     for($i=0; $i<$sizeof; $i++)  
     {  
          $totalfilesize += $games[$i]['swf_file_size'];
          $countfor++;  
     }  

     $startindx += 10;
     $endindx += 10;  
     $totalruns -= 1;  
     $totalgames += $sizeof;
     unset($games);  
}  

echo'<p>' . ' countwhile = ' . $countwhile . ' countfor = ' . $countfor . '</p>';
4

3 に答える 3

3

問題 1:

$sizeof = sizeof($games)-1;

説明 1:

for($i=0, $sizeof = sizeof($games);$i<=$sizeof;$i++)  

上記は 11 回実行されますが、これsizeof($games)は 10
なので、どちらか

for($i=1, $sizeof = sizeof($games);$i<=$sizeof;$i++)  

or

for($i=0, $sizeof=sizeof($games)-1;$i<=$sizeof;$i++)  

問題 2 :

$e = sizeof($games);

説明 2 :

$e = count($games);  
...
$e += $e;

の最終的なサイズ$gamesが 50 の場合、それを合計して 100 にするだけ
なので、何らかの論理的な問題が発生します。

于 2010-12-30T16:13:45.230 に答える
1

答えが受け入れられたことは知っていますが、リファクタリングしてこれをもう少しきれいにすると思いました。

function retrieveGamesInfo($limit, $start = 0)
{
  $feedHandler = new FeedHandler(); // ignore this, just for testing to simluate your call

  if ($start > $limit)
    throw new Exception("Start index must be within the limit");

  $result = Array(
    'TotalGames' => 0,
    'TotalFileSize' => 0
  );

  // iterate over the results in groups of 10
  $range = $start;
  while ($range < $limit)
  {
    $range_end = $range + 10; // change me to play with the grab amount
    if ($range_end > $limit)
      $range_end = $limit;

    // grab the next 10 entries
    $games = $feedHandler->getGames($range,$range_end);

    $result['TotalGames'] += count($games);

    foreach ($games as $game)
      $result['TotalFileSize'] += $game['swf_file_size'];

    $range = $range_end;
  }
  return $result;
}
var_dump(retrieveGamesInfo(50));

私が読んで取り入れたすべてのものに基づいているので、これは良い補足になるはずです. 上記により、次の結果が得られます。

array(2) {
  ["TotalGames"]=>
  int(50)
  ["TotalFileSize"]=>
  int(275520)
}
于 2010-12-30T17:34:09.150 に答える
0

私のコメントで述べたように、$e は各ループで上書きされるため、最後の $e にあるのは $games *2 の要素の最後のカウントです。ajrealの問題を追加すると、これは結果がコードがレンダリングすると予想されるものであることを意味します:-)そして、最後の$gameは10要素だけでなく50要素であると確信しています。

于 2010-12-30T16:18:57.653 に答える