douji0073 2017-04-11 05:57
浏览 31
已采纳

减少数组到字符串,避免foreach

I've an array to reduce to string, but I've to do MANY times so I would like to use some array PHP function (some combination of array_walk, array_reduce,...) but none fit my needs, but I belive there's a solution that I miss. The code have to be PHP5.6 compliant too.

$list =[
    'k1' => 'vA1 vA2 vA2',
    'k2' => 'vB1 vB2 vB2',
    'k3' => '',
    'k4' => 'vC1 vC2 vC2',
    'k5' => NULL,
    'k6' => 'vD1 vD2 vD2',
];

function reduce($list){
    $_buff="";
    $_sep="";
    foreach ($list as $k => $v){
        if($v===null){
            continue;
        }
        $_buff.="$_sep$k $v";
        $_sep="; ";
    }
    return $_buff;
}

echo reduce($list)."
";

The expected result is

k1 vA1 vA2 vA2; k2 vB1 vB2 vB2; k3 ; k4 vC1 vC2 vC2; k6 vD1 vD2 vD2

Please note the different behavior if value is an empty string or null.

  • 写回答

6条回答 默认 最新

  • drf21989 2017-04-11 06:46
    关注

    I dont think there will be significant execution time difference with foreach or any array_* function. It will matter only if records increase more than 100K I guess.

    $result = array();
    
    array_walk($list, function($value, $key) use (&$result) {
        if($value!==null) {
            $result[] = $key .' '. $value;
        }
    });
    
    print_r(implode('; ', $result));
    

    Why don't you compare the time taken from all answer and choose the best one ;)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?