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

发布于 2024-07-10 17:46:32 字数 476 浏览 5 评论 0原文

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

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

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

有更快的方法吗?

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.

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

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

Is there a faster way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

苍暮颜 2024-07-17 17:46:32

您可以使用 http_build_query() 来执行此操作。

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

You can use http_build_query() to do that.

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

安稳善良 2024-07-17 17:46:32

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

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

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"}]
撕心裂肺的伤痛 2024-07-17 17:46:32

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

所以我使用 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

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

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....

// 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 :)

薄情伤 2024-07-17 17:46:32

这是我的解决方案,例如 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>

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

<?

$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>
笑咖 2024-07-17 17:46:32

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

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

诗化ㄋ丶相逢 2024-07-17 17:46:32

我的解决方案:

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

My solution:

$url_string = http_build_query($your_arr);
$res = urldecode($url_string); 
热情消退 2024-07-17 17:46:32

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

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"
一梦浮鱼 2024-07-17 17:46:32
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) ;
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) ;
哑剧 2024-07-17 17:46:32

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

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

示例:

$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"

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

$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"
一萌ing 2024-07-17 17:46:32

为此,请使用 array_walk 。

$arr = [
    "key"  => "value",
    "key2" => "value2",
];

array_walk($arr, function(&$value, $key) {
    $value = "{$key}: {$value}";
});

implode("<br/>", $arr)

结果

key: value<br/>key2: value2<br/>

Use array_walk for this.

$arr = [
    "key"  => "value",
    "key2" => "value2",
];

array_walk($arr, function(&$value, $key) {
    $value = "{$key}: {$value}";
});

implode("<br/>", $arr)

Result

key: value<br/>key2: value2<br/>
橘和柠 2024-07-17 17:46:32

我喜欢@kostikovmu 的方法,因为它看起来比其他长代码更简单。 虽然这不正是我们所追求的..
我们寻找这种标头格式:“...key: value\r\n...”。

所以我用扩展公式来得到

urldecode(str_replace("=", ": ", http_build_query($headers,"", "\r\n")))

I liked the approach of @kostikovmu as it looks simpler than other long codes. though this is not exactly what we are after..
We look for this header format : "...key: value\r\n...".

So i used extended the fomula to get that

urldecode(str_replace("=", ": ", http_build_query($headers,"", "\r\n")))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文