Php get array data size

Having this array:

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

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

Is it possible? I searched google, but I found count(), and that’s not what I need to do this job.

Edit: Each of these blocks contains many other sub-blocks, and I thought about calculating the size of the data in bytes, because the counter does not do the work here.

+5
source share
4 answers

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

- :

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

$sizes , "" - , - .

: , , ​​:

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-.

+11
echo  mb_strlen(serialize((array)$arr), '8bit');
+11

Do you mean something like this?

$x = 32;
foreach($blocks as $key => $block)
{
  if(getArraySize($block) < $x)
  {
     //Do Something
  }else
  {
     //Do another thing
  }
}


//Recursive function
function getArraySize($array)
{
   $size = 0;
   foreach($array as $element)
   {
      if(is_array($element))
         $size += getArraySize($element);
      else
         $size += strlen($element);
   }

   return $size;
}
+2
source

To get the size in bytes, you can use the code below.

$serialized = serialize($foo);
if (function_exists('mb_strlen')) {
    $size = mb_strlen($serialized, '8bit');
} else {
    $size = strlen($serialized);
}

I hope this will be helpful.

+2
source

All Articles