迭代多维数组

时间:2012-02-17 22:58:51

标签: php arrays

我有一个数组,用于保存用作缓存的“单元格”图像:

/* make a symbol cell image with/without color and save it in the cache */
if(!isset($stitchCache[$r][$g][$b]))
{
  //create new image
  $stitchCache[$r][$g][$b] = imagecreatetruecolor(SYMBOL_SIZE,SYMBOL_SIZE);
  $stitchCacheColor = imagecolorallocate($stitchCache[$r][$g][$b], $r, $g, $b);
  //draw colored rectangle
  imagefilledrectangle($stitchCache[$r][$g][$b], 0, 0, SYMBOL_SIZE-1, SYMBOL_SIZE-1, $stitchCacheColor);
  //add the symbol
  $symbolFile=$stitchChartArray[$y][$x][1];
  if($symbolFile){
    $symbolImage = imagecreatefrompng($symbolFile);
    imagecopyresampled ($stitchCache[$r][$g][$b],$symbolImage,0,0,0,0,SYMBOL_SIZE-1,SYMBOL_SIZE-1,imagesx($symbolImage), imagesy($symbolImage) );
    imagedestroy($symbolImage);
  }
}

//add image from cache to the block image
imagecopyresampled ($newBlockImage,$stitchCache[$r][$g][$b],$stitchStartX, $stitchStartY,0,0,SYMBOL_SIZE,SYMBOL_SIZE,SYMBOL_SIZE,SYMBOL_SIZE);

我需要稍后销毁数组中的每个图像。我想出了这个,但这不正确。

//dump stitch cache
foreach($stitchCache as $r)
{
    foreach($stitchCache[$r] as $g)
    {
        foreach($stitchCache[$r][$g] as $b)
        {
            imagedestroy($stitchCache[$r][$g][$b]);
        }
    }
}

再次感谢你, 托德

1 个答案:

答案 0 :(得分:1)

为什么不在调用imagecopyresampled之后立即将其销毁?除非你遗漏了代码,否则就是我要做的。

foreach($stitchCache as $rk => $r)
{
    foreach($r as $gk => $g)
    {
        foreach($g as $bk => $b)
        {
            imagedestroy($stitchCache[$rk][$gk][$bk]);
        }
    }
}