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 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式