Reputation: 7688
Having this array:
Array
(
[_block1] => Array
(
[list] => Array
(
[sub-list] => Array
(
)
)
[links] => Number
[total] => Number
...
)
[_block2] => Array
(
[@attributes] => Array
(
)
[title] => ...
[data] => Array ()
...
)
[_block3] => Array
(
..
)
)
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.
Is it possible? I have searched google but I only found count()
and that isn't what I need to make this work.
Edit: 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.
Upvotes: 14
Views: 39240
Reputation: 354
Get array size in bytes:
<?php
$array = [1, 2, 3];
$json = json_encode($array); // JSON_PRETTY_PRINT for multiline json formatting
echo mb_strlen($json, '8bit') . " bytes\n"; // output - 7 bytes
// for multidimensional array
$array = [['a','b','c'], ['e','f','g']];
$json = json_encode($array, JSON_FORCE_OBJECT); // JSON_PRETTY_PRINT | JSON_FORCE_OBJECT for multiline json formatting
echo mb_strlen($json, '8bit') . " bytes\n"; // output - 61 bytes
Upvotes: 2
Reputation: 121
To get the size in bytes you can use the below code.
$serialized = serialize($foo);
if (function_exists('mb_strlen')) {
$size = mb_strlen($serialized, '8bit');
} else {
$size = strlen($serialized);
}
I hope it will be helpful.
Upvotes: 6
Reputation: 13003
If I understood well your question, you need the size of each "block" subarray inside the main array.
You can do something like this:
$sizes = array();
foreach($returnedArray as $key => $content) {
$sizes[$key] = count($content);
}
The $sizes
array will be an associative array which the various "block"s as keys and the size of the data as values.
Edit: 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;
}
assuming to have only ASCII-encoded strings.
Upvotes: 16
Reputation: 10067
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;
}
Upvotes: 5