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

Fastest way to implode an associative array with keys

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

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

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

有没有更快的方法?


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

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


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

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

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

因此,我使用PHP的array_walk()函数进行了此操作,使我可以将关联数组加入参数列表中,然后可以将这些参数应用于HTML标记....

1
2
3
4
5
6
7
8
// 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

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


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?

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

?>

 >
    <img src="http://example.com/images/best-of.jpg" alt="">

一种使用print_r(array, true)的方式,它将返回数组

的字符串表示形式


我的解决方案:

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

使用array_walk

可以使它更短,更透明但更直观

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$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"

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

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

例子:

1
2
3
4
5
6
7
8
9
$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"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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) ;

这是我能想到的最基本的版本:

1
2
3
4
5
public function implode_key($glue ="", $pieces = array())
{
    $keys = array_keys($pieces);
    return implode($glue, $keys);
}


1
echo implode(",", array_keys($companies->toArray()));

$companies->toArray()-
如果您的$variable是对象,以防万一,否则只需传递$ companies。

就是这样!