如何在 PHP 中不使用 foreach 用键和值内爆数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11427398/
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-25 00:30:31  来源:igfitidea点击:

How to implode array with key and value without foreach in PHP

phparraysstringimplode

提问by tom91136

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.

implode()已经想到了,但它并没有用它来破坏钥匙。

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

如果需要foreach,是否可以不嵌套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/UPDATE:这个问题是很久以前被问到的。那时,我想将所有内容都写在一行中,因此我会使用三元运算符并嵌套内置函数调用以支持 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 放在函数中将比编写单行代码更具可读性和模块化(即使所有答案都很棒!)。

回答by stewe

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

演示

回答by Yoshi

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

回答by Maxim Tkach

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"

目标:获取一行 1,000 项,格式如下:“key:value,key2:value2”

We have array (for example):

我们有数组(例如):

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

Test number one:

测试一:

Use http_build_queryand str_replace:

使用http_build_querystr_replace

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

Average time to implode 1000 elements: 0.00012930955084904

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

Test number two:

测试二:

Use array_mapand implode:

使用array_map和内

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:

测试三:

Use array_walkand 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:

测试四:

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

回答by Madara's Ghost

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.

虽然它不会给你你想要的确切结果字符串,但以后编码/存储/检索/解码会容易得多。

回答by Shiplu Mokaddim

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

回答by Sergey Yurich

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

回答by Bj?rn

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

如果你想在没有最后一个 $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, ",");

回答by nickl-

There is also var_exportand print_rmore commonly known for printing debug output but both functions can take an optional argument to return a string instead.

还有var_exportprint_r更常用于打印调试输出,但这两个函数都可以采用可选参数来返回字符串。

Using the example from the question as data.

使用问题中的示例作为数据。

$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];

Using print_rto turn the array into a string

使用print_r把所述阵列成一个字符串

This will output a human readable representation of the variable.

这将输出变量的人类可读表示。

$string = print_r($array, true);
echo $string;

Will output:

将输出:

Array
(
    [item1] => object1
    [item2] => object2
    [item-n] => object-n
)

Using var_exportto turn the array into a string

使用var_export把所述阵列成一个字符串

Which will output a php string representation of the variable.

这将输出变量的 php 字符串表示。

$string = var_export($array, true);
echo $string;

Will output:

将输出:

array (
  'item1' => 'object1',
  'item2' => 'object2',
  'item-n' => 'object-n',
)

Because it is valid php we can evaluate it.

因为它是有效的 php 我们可以评估它。

eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);

Outputs:

输出:

bool(true)

回答by sapenov

You could use PHP's array_reduceas 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");

回答by Ajay Patidar

For create mysql where conditions from array

用于创建 mysql where 数组中的条件

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