问题描述
没有 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'
我已经考虑过 implode()
,但它并没有用它来内爆密钥.
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/更新:这个问题很久以前就被问到了.那时,我想将所有内容都写在一行中,因此我会使用三元运算符并嵌套内置函数调用以支持 foreach.这不是一个好习惯!写出可读性强的代码,简洁与否无所谓.
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 用键和值内爆数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!