在PHP中如何在没有foreach的情况下使用键和值内爆数组

时间:2022-02-15 22:09:08

Without foreach, how can I turn an array like this

没有foreach,我怎么能像这样旋转一个数组

array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");

to a string like this

像这样的弦。

item1='object1', item2='object2',.... item-n='object-n'

I thought about implode() already, but it doesn't implode the key with it.

我已经考虑过内爆(),但是它并没有内爆键。

If foreach it necessary, is it possible to not nest the foreach?

如果有必要,有可能不为每个人筑窝吗?

EDIT: I've changed the string

编辑:我改变了字符串


EDIT2/UPDATE: This question was asked quite a while ago. At that time, I wanted to write everything in one line so I would use ternary operators and nest built in function calls in favor of foreach. That was not a good practice! Write code that is readable, whether it is concise or not doesn't matter that much.

EDIT2/更新:这个问题已经被问了很久了。当时,我想把所有内容都写在一行中,这样我就可以使用三元运算符和在函数调用中构建的nest来支持foreach。这不是一个好习惯!编写可读的代码,不管它是否简洁,都没有多大关系。

In this case: putting the foreach in a function will be much more readable and modular than writing a one-liner(Even though all the answers are great!).

在这种情况下,将foreach放在函数中会比编写一行程序更容易阅读和模块化(尽管所有的答案都很棒!)

10 个解决方案

#1


135  

and another way:

和另一种方式:

$input = array(    'item1'  => 'object1',    'item2'  => 'object2',    'item-n' => 'object-n');$output = implode(', ', array_map(    function ($v, $k) {        if(is_array($v)){            return $k.'[]='.implode('&'.$k.'[]=', $v);        }else{            return $k.'='.$v;        }    },     $input,     array_keys($input)));

or:

或者:

$output = implode(', ', array_map(    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },    $input,    array_keys($input)));

#2


125  

You could use http_build_query, like this:

您可以使用http_build_query,如下所示:

<?php  $a=array("item1"=>"object1", "item2"=>"object2");  echo http_build_query($a,'',', ');?>

Output:

输出:

item1=object1, item2=object2 

Demo

演示

#3


17  

I spent measurements (100000 iterations), what fastest way to glue an associative array?

我使用了度量(100000次迭代),用什么最快的方法来粘合一个关联数组?

Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"

目的:获取一行1000个条目,格式为:“key:value,key2:value2”

We have array (for example):

我们有数组(例如):

$array = [    'test0' => 344,    'test1' => 235,    'test2' => 876,    ...];

Test number one:

测试数量:

Use http_build_query and str_replace:

使用http_build_query:大小写不敏感

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

内爆1000个元素的平均时间:0.00012930955084904

Test number two:

测试二:

Use array_map and implode:

使用到和内爆:

implode(',', array_map(        function ($v, $k) {            return $k.':'.$v;        },        $array,        array_keys($array)    ));

Average time to implode 1000 elements: 0.0004890081976675

内爆1000个元素的平均时间:0.0004890081976675

Test number three:

测试3号:

Use array_walk and implode:

用array_walk和内爆:

array_walk($array,        function (&$v, $k) {            $v = $k.':'.$v;        }    );implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

平均内爆时间为1000个元素:0.0003874126245348

Test number four:

测试4号:

Use foreach:

使用foreach:

    $str = '';    foreach($array as $key=>$item) {        $str .= $key.':'.$item.',';    }    rtrim($str, ',');

Average time to implode 1000 elements: 0.00026632803902445

平均内爆时间1000个元素:0.00026632803902445

I can conclude that the best way to glue the array - use http_build_query and str_replace

我可以得出这样的结论:最好的方法是使用http_build_query和str_replace。

#4


4  

I would use serialize() or json_encode().

我将使用serialize()或json_encode()。

While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.

虽然它不会给出您想要的确切结果字符串,但稍后对其进行编码/存储/检索/解码要容易得多。

#5


3  

Using array_walk

使用array_walk

$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");$r=array();array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));echo implode(', ', $r);

IDEONE

IDEONE

#6


2  

Change

改变

-    return substr($result, (-1 * strlen($glue)));+    return substr($result, 0, -1 * strlen($glue));

if you want to resive the entire String without the last $glue

如果你想要在不使用最后一美元胶水的情况下压缩整个字符串

function key_implode(&$array, $glue) {    $result = "";    foreach ($array as $key => $value) {        $result .= $key . "=" . $value . $glue;    }    return substr($result, (-1 * strlen($glue)));}

And the usage:

和用法:

$str = key_implode($yourArray, ",");

#7


2  

For debugging purposes. Recursive write an array of nested arrays to a string.Used foreach. Function stores National Language characters.

用于调试目的。递归地将嵌套数组写入字符串中。使用foreach。函数存储国家语言字符。

function q($input){    $glue = ', ';    $function = function ($v, $k) use (&$function, $glue) {        if (is_array($v)) {            $arr = [];            foreach ($v as $key => $value) {                $arr[] = $function($value, $key);            }            $result = "{" . implode($glue, $arr) . "}";        } else {            $result = sprintf("%s=\"%s\"", $k, var_export($v, true));        }        return $result;    };    return implode($glue, array_map($function, $input, array_keys($input))) . "\n";}

#8


0  

You could use PHP's array_reduce as well,

也可以使用PHP的array_reduce,

$a = ['Name' => 'Last Name'];function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}$imploded = array_reduce(array_keys($a), "acc");

#9


0  

For create mysql where conditions from array

用于创建mysql,其中条件来自数组

$sWheres = array('item1'  => 'object1',                 'item2'  => 'object2',                 'item3'  => 1,                 'item4'  => array(4,5),                 'item5'  => array('object3','object4'));$sWhere = '';if(!empty($sWheres)){    $sWhereConditions = array();    foreach ($sWheres as $key => $value){        if(!empty($value)){            if(is_array($value)){                $value = array_filter($value); // For remove blank values from array                if(!empty($value)){                    array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'                    $sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));                }            }else{                $sWhereConditions[] = sprintf("%s='%s'", $key, $value);            }        }    }    if(!empty($sWhereConditions)){        $sWhere .= "(".implode(' AND ', $sWhereConditions).")";    }}echo $sWhere;  // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))

#10


0  

Here is a simple example, using class:

这里有一个简单的例子,使用类:

$input = array(    'element1'  => 'value1',    'element2'  => 'value2',    'element3' =>  'value3');echo FlatData::flatArray($input,', ', '=');class FlatData{    public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')    {        $output = implode($separator_elements, array_map(            function ($v, $k, $s) {                return sprintf("%s{$s}%s", $k, $v);            },            $input,            array_keys($input),            array_fill(0, count($input), $separator)        ));      return $output;    }}

#1


135  

and another way:

和另一种方式:

$input = array(    'item1'  => 'object1',    'item2'  => 'object2',    'item-n' => 'object-n');$output = implode(', ', array_map(    function ($v, $k) {        if(is_array($v)){            return $k.'[]='.implode('&'.$k.'[]=', $v);        }else{            return $k.'='.$v;        }    },     $input,     array_keys($input)));

or:

或者:

$output = implode(', ', array_map(    function ($v, $k) { return sprintf("%s='%s'", $k, $v); },    $input,    array_keys($input)));

#2


125  

You could use http_build_query, like this:

您可以使用http_build_query,如下所示:

<?php  $a=array("item1"=>"object1", "item2"=>"object2");  echo http_build_query($a,'',', ');?>

Output:

输出:

item1=object1, item2=object2 

Demo

演示

#3


17  

I spent measurements (100000 iterations), what fastest way to glue an associative array?

我使用了度量(100000次迭代),用什么最快的方法来粘合一个关联数组?

Objective: To obtain a line of 1,000 items, in this format: "key:value,key2:value2"

目的:获取一行1000个条目,格式为:“key:value,key2:value2”

We have array (for example):

我们有数组(例如):

$array = [    'test0' => 344,    'test1' => 235,    'test2' => 876,    ...];

Test number one:

测试数量:

Use http_build_query and str_replace:

使用http_build_query:大小写不敏感

str_replace('=', ':', http_build_query($array, null, ','));

Average time to implode 1000 elements: 0.00012930955084904

内爆1000个元素的平均时间:0.00012930955084904

Test number two:

测试二:

Use array_map and implode:

使用到和内爆:

implode(',', array_map(        function ($v, $k) {            return $k.':'.$v;        },        $array,        array_keys($array)    ));

Average time to implode 1000 elements: 0.0004890081976675

内爆1000个元素的平均时间:0.0004890081976675

Test number three:

测试3号:

Use array_walk and implode:

用array_walk和内爆:

array_walk($array,        function (&$v, $k) {            $v = $k.':'.$v;        }    );implode(',', $array);

Average time to implode 1000 elements: 0.0003874126245348

平均内爆时间为1000个元素:0.0003874126245348

Test number four:

测试4号:

Use foreach:

使用foreach:

    $str = '';    foreach($array as $key=>$item) {        $str .= $key.':'.$item.',';    }    rtrim($str, ',');

Average time to implode 1000 elements: 0.00026632803902445

平均内爆时间1000个元素:0.00026632803902445

I can conclude that the best way to glue the array - use http_build_query and str_replace

我可以得出这样的结论:最好的方法是使用http_build_query和str_replace。

#4


4  

I would use serialize() or json_encode().

我将使用serialize()或json_encode()。

While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.

虽然它不会给出您想要的确切结果字符串,但稍后对其进行编码/存储/检索/解码要容易得多。

#5


3  

Using array_walk

使用array_walk

$a = array("item1"=>"object1", "item2"=>"object2","item-n"=>"object-n");$r=array();array_walk($a, create_function('$b, $c', 'global $r; $r[]="$c=$b";'));echo implode(', ', $r);

IDEONE

IDEONE

#6


2  

Change

改变

-    return substr($result, (-1 * strlen($glue)));+    return substr($result, 0, -1 * strlen($glue));

if you want to resive the entire String without the last $glue

如果你想要在不使用最后一美元胶水的情况下压缩整个字符串

function key_implode(&$array, $glue) {    $result = "";    foreach ($array as $key => $value) {        $result .= $key . "=" . $value . $glue;    }    return substr($result, (-1 * strlen($glue)));}

And the usage:

和用法:

$str = key_implode($yourArray, ",");

#7


2  

For debugging purposes. Recursive write an array of nested arrays to a string.Used foreach. Function stores National Language characters.

用于调试目的。递归地将嵌套数组写入字符串中。使用foreach。函数存储国家语言字符。

function q($input){    $glue = ', ';    $function = function ($v, $k) use (&$function, $glue) {        if (is_array($v)) {            $arr = [];            foreach ($v as $key => $value) {                $arr[] = $function($value, $key);            }            $result = "{" . implode($glue, $arr) . "}";        } else {            $result = sprintf("%s=\"%s\"", $k, var_export($v, true));        }        return $result;    };    return implode($glue, array_map($function, $input, array_keys($input))) . "\n";}

#8


0  

You could use PHP's array_reduce as well,

也可以使用PHP的array_reduce,

$a = ['Name' => 'Last Name'];function acc($acc,$k)use($a){ return $acc .= $k.":".$a[$k].",";}$imploded = array_reduce(array_keys($a), "acc");

#9


0  

For create mysql where conditions from array

用于创建mysql,其中条件来自数组

$sWheres = array('item1'  => 'object1',                 'item2'  => 'object2',                 'item3'  => 1,                 'item4'  => array(4,5),                 'item5'  => array('object3','object4'));$sWhere = '';if(!empty($sWheres)){    $sWhereConditions = array();    foreach ($sWheres as $key => $value){        if(!empty($value)){            if(is_array($value)){                $value = array_filter($value); // For remove blank values from array                if(!empty($value)){                    array_walk($value, function(&$item){ $item = sprintf("'%s'", $item); }); // For make value string type 'string'                    $sWhereConditions[] = sprintf("%s in (%s)", $key, implode(', ', $value));                }            }else{                $sWhereConditions[] = sprintf("%s='%s'", $key, $value);            }        }    }    if(!empty($sWhereConditions)){        $sWhere .= "(".implode(' AND ', $sWhereConditions).")";    }}echo $sWhere;  // (item1='object1' AND item2='object2' AND item3='1' AND item4 in ('4', '5') AND item5 in ('object3', 'object4'))

#10


0  

Here is a simple example, using class:

这里有一个简单的例子,使用类:

$input = array(    'element1'  => 'value1',    'element2'  => 'value2',    'element3' =>  'value3');echo FlatData::flatArray($input,', ', '=');class FlatData{    public static function flatArray(array $input = array(), $separator_elements = ', ', $separator = ': ')    {        $output = implode($separator_elements, array_map(            function ($v, $k, $s) {                return sprintf("%s{$s}%s", $k, $v);            },            $input,            array_keys($input),            array_fill(0, count($input), $separator)        ));      return $output;    }}