如何用爆键和值数组没有在PHP的foreach [英] How to implode array with key and value without foreach in PHP
问题描述
如果没有的foreach
我怎么可以把这样的数组
Without foreach, how can I turn an array like this
array("item1"=>"object1", "item2"=>"object2",......."item-n"=>"object-n");
像这样的字符串
item1='object1', item2='object2',.... item-n='object-n'
我想到了破灭()
了,但它并没有与它破灭的关键。
I thought about implode()
already, but it doesn't implode the key with it.
如果的foreach有必要,是否有可能不能嵌套在foreach?
If foreach it necessary, is it possible to not nest the foreach?
编辑:我已经改变了字符串
EDIT2 / UPDATE:
这个问题在相当长的一段前问道。当时,我想在一行中写的一切,所以我会用三元运营商和巢建在赞成的foreach的函数调用。这是不是一个好的做法!写code,它是可读的,无论是简洁与否不管那么多了。
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.
在这种情况下:(!即使所有的答案是伟大的),将在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!).
推荐答案
和另一种方式:
$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)
));
或
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
这篇关于如何用爆键和值数组没有在PHP的foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!