Fastest way to implode an associative array with keys

后端 未结 11 1771
梦如初夏
梦如初夏 2020-12-07 19:42

I\'m looking for a fast way to turn an associative array in to a string. Typical structure would be like a URL query string but with customizable separators so I can use \'<

11条回答
  •  爱一瞬间的悲伤
    2020-12-07 20:14

    What about this shorter, more transparent, yet more intuitive with array_walk

    $attributes = array(
      'data-href'   => 'http://example.com',
      'data-width'  => '300',
      'data-height' => '250',
      'data-type'   => 'cover',
    );
    
    $args = "";
    array_walk(
        $attributes, 
        function ($item, $key) use (&$args) {
            $args .= $key ." = '" . $item . "' ";  
        }
    );
    // output: 'data-href="http://example.com" data-width="300" data-height="250" data-type="cover"
    

提交回复
热议问题