dsgsdg206050
dsgsdg206050
2014-02-18 21:31
浏览 9
已采纳

数密钥长度php

I can't find anywhere how to make an array with the keys and the character length of that key.

Example:

<?php
$array = array("ab" => 145, "bassfasdf" => 13, "cdfsa" => 2684);


print_r($array);
?>

I would like it to output this:

Array
(
    [ab] => 2
    [bassfasdf] => 9
    [cdfsa] => 5
)

Does anyone have any idea on how to do that?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongxie8856
    dongxie8856 2014-02-18 21:33
    已采纳
    $array = array("ab" => 145, "bassfasdf" => 13, "cdfsa" => 2684);
    foreach ($array as $key => &$value) {
       $value = strlen($key);
    }
    
    点赞 评论
  • douxing6532
    douxing6532 2014-02-18 21:36

    Might be a shorter way:

    $result = array_combine($keys=array_keys($array), array_map('strlen', $keys));
    
    点赞 评论
  • duanjuan3931
    duanjuan3931 2014-02-18 21:37

    You could use an array_map function, or a foreach loop as shown below:

    $array = array("ab" => 145, "bassfasdf" => 13, "cdfsa" => 2684);
    $keyLengths = array();
    foreach ($array as $key=>$value)
    {
        $keyLengths[$key] = strlen($key);
    }
    
    点赞 评论

相关推荐