php - 获取多维 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在这里。
解决方案
你总是可以数数:
$count = array_map('count', $myArray);
这将为您提供一个包含所有子数组计数的数组。但是,您的做法还不错。
推荐阅读
- javascript - if else 基于内容 div 的 javascript 条件
- html - 原始 HTML 到 R:转换文本通过函数到 div("text",class="x")
- python - 当我尝试使用 python networkx 总结文本文档时出现错误“功率迭代未能在 100 次迭代内收敛”)
- apache-kafka - 在同一 Kafka 流应用程序中重用 KStream 对象以跨多个时间窗口查找计数
- javascript - React JSX 传播属性如何在幕后工作?
- html - 设置其他元素的浮动左侧后,位置粘性不起作用
- rust - Rust 中有 ++ 和 -- 运算符吗?
- java - 我能知道为什么我的汇总结果不起作用吗
- html - 如何水平显示图像及其标题
- python - 从列表中查找值的索引到不同的列表