首页 > 解决方案 > 获取多维 PHP 数组大小的最便宜方法

问题描述

我有一个多维数组。如果它总共包含少于阈值的$threshold = 1000位/字节/任何数据,包括它的键,我想获取更多内容。

在性能/内存方面,获得近似数组大小的最便宜的方法是什么?

现在,我使用strlen(serialize($array)). 根据评论更新:

$threshold = 1000;
$myArray = array(
    'size' => 0,
    'items' => array(
        ['id' => 1, 'content' => 'Lorem ipsum'],
        ['id' => 2, 'content' => 'Dolor sit'],
        ['id' => 3, 'content' => 'Amet']
    )
);

while($myArray['size'] < $threshold)
{
    echo "Array size is below threshold.<br/>";
    addStuffToArray($myArray);
}

function addStuffToArray(&$arr)
{
     echo "Adding stuff to array.<br/>";
     $newArrayItem = array(
         'id' => rand(0, 10000),
         'content' => rand(999999, 999999)
     );
     $arr['size'] += strlen(serialize($newArrayItem));
     $arr['items'][] = $newArrayItem;
}

PHPFiddle在这里

标签: phparrays

解决方案


你总是可以数数:

$count = array_map('count', $myArray);

这将为您提供一个包含所有子数组计数的数组。但是,您的做法还不错。


推荐阅读