获取数组中的字符数?

时间:2017-03-11 18:00:34

标签: php arrays http content-length

我想用http请求发送内容长度。对于普通字符串,我可以使用函数strlen()。但是如何在PHP中专门为多维数组使用数组呢?我找到了以下脚本来提取像var_dump()这样的数组。但是我对Content-Length需要什么?

function count_array_chars($array){
  foreach($array as $key => $value){
      if (!is_array($value))
      {
          echo $key ." => ". $value ."\r\n" ;
      }
      else
      {
         echo $key ." => array( \r\n";

         foreach ($value as $key2 => $value2)
         {
             echo "\t". $key2 ." => ". $value2 ."\r\n";
         }

         echo ")";
      }
  }
}

更新

$data_array = array(
    "end"=>array("dateTime"=>$end),
    "start"=>array("dateTime"=>$start),
    "summary"=>$name
  );

2 个答案:

答案 0 :(得分:2)

假设您只想计算值,可以使用此方法:

$array = array(
    "1" => "abcd",
    "2" => "xyz"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val) use (&$charNumber)
    {
        $charNumber += strlen($val);
    });
    return $charNumber;
}

print count_array_chars($array);

如果您还想计算密钥,它看起来像是:

$array = array(
    "end" => array("dateTime"=>"end"),
    "start" => array("dateTime"=>"start"),
    "summary" => "name"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val, $key) use (&$charNumber)
    {
        $charNumber += strlen($val) + strlen($key);
    });
    return $charNumber;
}

print count_array_chars($array);

答案 1 :(得分:0)

由于您希望将数组作为http请求的一部分发送,因此您可以使用http_build_query进行准备并计算strlen返回的链的http_build_query

<?php

$data_array = array(
    "end"=>array("dateTime"=>'end'),
    "start"=>array("dateTime"=>'start'),
    "summary"=>'name'
  );

$http_build_query = http_build_query($data_array);
echo strlen($http_build_query);