Fastest way to implode an associative array with keys

后端 未结 11 1764
梦如初夏
梦如初夏 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:15
    function array_to_attributes ( $array_attributes )
    {
    
        $attributes_str = NULL;
        foreach ( $array_attributes as $attribute => $value )
        {
    
            $attributes_str .= " $attribute=\"$value\" ";
    
        }
    
        return $attributes_str;
    }
    
    $attributes = array(
        'data-href'   => 'http://example.com',
        'data-width'  => '300',
        'data-height' => '250',
        'data-type'   => 'cover',
    );
    
    echo array_to_attributes($attributes) ;
    
    0 讨论(0)
  • 2020-12-07 20:23

    This is the most basic version I can think of:

    public function implode_key($glue = "", $pieces = array())
    {
        $keys = array_keys($pieces);
        return implode($glue, $keys);
    }
    
    0 讨论(0)
  • 2020-12-07 20:24

    If you're not concerned about the exact formatting however you do want something simple but without the line breaks of print_r you can also use json_encode($value) for a quick and simple formatted output. (note it works well on other data types too)

    $str = json_encode($arr);
    //output...
    [{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]
    
    0 讨论(0)
  • 2020-12-07 20:25

    My solution:

    $url_string = http_build_query($your_arr);
    $res = urldecode($url_string); 
    
    0 讨论(0)
  • 2020-12-07 20:26

    You can use http_build_query() to do that.

    Generates a URL-encoded query string from the associative (or indexed) array provided.

    0 讨论(0)
提交回复
热议问题