php 用键内爆关联数组的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/408032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:38:31  来源:igfitidea点击:

Fastest way to implode an associative array with keys

phparraysquery-stringassociative-arrayimplode

提问by matpie

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 '&' for xhtml links or '&' otherwise.

我正在寻找一种将关联数组转换为字符串的快速方法。典型的结构类似于 URL 查询字符串,但具有可自定义的分隔符,因此我可以使用 ' &' 表示 xhtml 链接,&否则使用 ' ' 。

My first inclination is to use foreachbut since my method could be called many times in one request I fear it might be too slow.

我的第一个倾向是使用,foreach但由于我的方法可以在一个请求中多次调用,我担心它可能太慢了。

<?php
$Amp = $IsXhtml ? '&amp;' : '&';
$Parameters = array('Action' => 'ShowList', 'Page' => '2');
$QueryString = '';
foreach ($Parameters as $Key => $Value)
        $QueryString .= $Amp . $Key . '=' . $Value;

Is there a faster way?

有没有更快的方法?

回答by Greg

You can use http_build_query()to do that.

你可以用它http_build_query()来做到这一点。

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

从提供的关联(或索引)数组生成 URL 编码的查询字符串。

回答by matpie

As an aside, I was in search to find the best way to implode an associative array but using my own seperators etc...

顺便说一句,我正在寻找内爆关联数组的最佳方法,但使用我自己的分隔符等......

So I did this using PHP's array_walk() function to let me join an associative array into a list of parameters that could then be applied to a HTML tag....

所以我使用 PHP 的 array_walk() 函数做到了这一点,让我将一个关联数组加入到一个参数列表中,然后可以将这些参数应用于 HTML 标签......

// Create Params Array
$p = Array("id"=>"blar","class"=>"myclass","onclick"=>"myJavascriptFunc()");

// Join Params
array_walk($p, create_function('&$i,$k','$i=" $k=\"$i\"";'));
$p_string = implode($p,"");

// Now use $p_string for your html tag

Obviously, you could stick that in your own function somehow but it gives you an idea of how you can join an associative array using your own method. Hope that helps someone :)

显然,您可以以某种方式将其粘贴到您自己的函数中,但它可以让您了解如何使用自己的方法连接关联数组。希望对某人有所帮助:)

回答by scunliffe

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

如果您不关心确切的格式,但是您确实想要一些简单但没有换行符的内容,print_r您也可以使用json_encode($value)快速简单的格式化输出。(注意它也适用于其他数据类型

$str = json_encode($arr);
//output...
[{"id":"123","name":"Ice"},{"id":"234","name":"Cake"},{"id":"345","name":"Pie"}]

回答by user4846194

This is my solution for example for an div data-attributes:

这是我的解决方案,例如 div 数据属性:

<?

$attributes = array(
    'data-href'   => 'http://example.com',
    'data-width'  => '300',
    'data-height' => '250',
    'data-type'   => 'cover',
);

$dataAttributes = array_map(function($value, $key) {
    return $key.'="'.$value.'"';
}, array_values($attributes), array_keys($attributes));

$dataAttributes = implode(' ', $dataAttributes);

?>

<div class="image-box" <?= $dataAttributes; ?> >
    <img src="http://example.com/images/best-of.jpg" alt="">
</div>

回答by dino.keco

One way is using print_r(array, true)and it will return string representation of array

一种方法是使用print_r(array, true),它将返回数组的字符串表示

回答by Softmixt

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) ;

回答by WackGet

A one-liner for creating string of HTML attributes (with quotes) from a simple array:

用于从简单数组创建 HTML 属性字符串(带引号)的单行:

$attrString = str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

Example:

例子:

$attrArray = array("id"    => "email", 
                   "name"  => "email",
                   "type"  => "email",
                   "class" => "active large");

echo str_replace("+", " ", str_replace("&", "\" ", str_replace("=", "=\"", http_build_query($attrArray)))) . "\"";

// Output:
// id="email" name="email" type="email" class="active large"

回答by kostikovmu

My solution:

我的解决方案:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 

回答by FentomX1

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

这个更短、更透明、更直观的 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"

回答by Justin

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);
}