PHP获取数组的数据大小 [英] php get array's data size

查看:899
本文介绍了PHP获取数组的数据大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有此数组:

Array
(
    [_block1] => Array
        (
            [list] => Array
            (
                 [sub-list] => Array
                 (
                 )
            )
            [links] => Number
            [total] => Number
            ...
        )
    [_block2] => Array
        (
             [@attributes] => Array
             (
             )
             [title] => ...
             [data] => Array ()
             ...
        )
    [_block3] => Array
        (
             ..
        )
)

这些块包含api返回的数据.知道每个api以不同的方式/结构返回数据后,我需要测量/计算每个api和其中一个的内部数据/大小,然后执行if data > X或<做点什么.

Those blocks contain data returned by api. Knowing that each api returns data in a different way/structure I need to measure/calculate the data/size inside of each and one of them and then do if data > X or < do something.

有可能吗?我已经搜索过google,但只找到count(),而这不是我要做的工作.

Is it possible? I have searched google but I only found count() and that isn't what I need to make this work.

这些块中的每个块都包含许多其他子块,我当时正在考虑以字节为单位计算数据大小,因为在这里count不能完成工作.

Each and of the those blocks contain many other sub blocks, and I was thinking of calculating the data size in bytes, because count wont do the job here.

推荐答案

如果我很了解您的问题,则需要主数组中每个块"子数组的大小.

If I understood well your question, you need the size of each "block" subarray inside the main array.

您可以执行以下操作:

$sizes = array();
foreach($returnedArray as $key => $content) {
    $sizes[$key] = count($content);
}

$sizes数组将是一个关联数组,其中各种块"作为键,而数据的大小作为值.

The $sizes array will be an associative array which the various "block"s as keys and the size of the data as values.

编辑问题后,如果最里面的数组中的数据是字符串还是整数,则可以使用如下函数:

after the edit of the question, if the data inside the innermost arrays are strings or integers you can use a function like this:

function getSize($arr) {
    $tot = 0;
    foreach($arr as $a) {
        if (is_array($a)) {
            $tot += getSize($a);
        }
        if (is_string($a)) {
            $tot += strlen($a);
        }
        if (is_int($a)) {
            $tot += PHP_INT_SIZE;
        }
    }
    return $tot;
}

假设只有ASCII编码的字符串.

assuming to have only ASCII-encoded strings.

这篇关于PHP获取数组的数据大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆