Say I have an array of key/value pairs in PHP:
假设我在PHP中有一个键/值对数组:
array( 'foo' => 'bar', 'baz' => 'qux' );
What's the simplest way to transform this to an array that looks like the following?
将它转换为如下所示的数组的最简单方法是什么?
array( 'foo=bar', 'baz=qux' );
i.e.
即。
array( 0 => 'foo=bar', 1 => 'baz=qux');
In perl, I'd do something like
在perl中,我会做一些类似的事情。
map { "$_=$hash{$_}" } keys %hash
Is there something like this in the panoply of array functions in PHP? Nothing I looked at seemed like a convenient solution.
在PHP的数组函数中有这样的东西吗?我看到的任何东西都不像是一个方便的解决方案。
4 个解决方案
#1
9
function parameterize_array($array) {
$out = array();
foreach($array as $key => $value)
$out[] = "$key=$value";
return $out;
}
#2
13
Another option for this problem: On PHP 5.3+ you can use array_map()
with a closure (you can do this with PHP prior 5.2, but the code will get quite messy!).
这个问题的另一个选择是:在PHP 5.3+上,您可以使用array_map()和闭包(您可以在之前的5.2中使用PHP,但是代码会变得非常混乱!)
"Oh, but on
array_map()
you only get the value!".“哦,但是在array_map()上,你只能得到值!”
Yeah, that's right, but we can map more than one array! :)
是的,没错,但是我们可以映射多个数组!:)
$arr = array( 'foo' => 'bar', 'baz' => 'qux' );
$result = array_map(function($k, $v){
return "$k=$v";
}, array_keys($arr), array_values($arr));
#3
3
A "curious" way to do it =P
这是一种“奇怪”的方法=P
// using '::' as a temporary separator, could be anything provided
// it doesn't exist elsewhere in the array
$test = split( '::', urldecode( http_build_query( $test, '', '::' ) ) );
#4
0
chaos' answer is nice and straightfoward. For a more general sense though, you might have missed the array_map()
function which is what you alluded to with your map { "$_=$hash{$_}" } keys %hash
example.
混沌的答案很简单。但是,对于更一般的意义,您可能忽略了array_map()函数,这是您在映射{“$_=$hash{$_}”}%hash示例中提到的。
#1
9
function parameterize_array($array) {
$out = array();
foreach($array as $key => $value)
$out[] = "$key=$value";
return $out;
}
#2
13
Another option for this problem: On PHP 5.3+ you can use array_map()
with a closure (you can do this with PHP prior 5.2, but the code will get quite messy!).
这个问题的另一个选择是:在PHP 5.3+上,您可以使用array_map()和闭包(您可以在之前的5.2中使用PHP,但是代码会变得非常混乱!)
"Oh, but on
array_map()
you only get the value!".“哦,但是在array_map()上,你只能得到值!”
Yeah, that's right, but we can map more than one array! :)
是的,没错,但是我们可以映射多个数组!:)
$arr = array( 'foo' => 'bar', 'baz' => 'qux' );
$result = array_map(function($k, $v){
return "$k=$v";
}, array_keys($arr), array_values($arr));
#3
3
A "curious" way to do it =P
这是一种“奇怪”的方法=P
// using '::' as a temporary separator, could be anything provided
// it doesn't exist elsewhere in the array
$test = split( '::', urldecode( http_build_query( $test, '', '::' ) ) );
#4
0
chaos' answer is nice and straightfoward. For a more general sense though, you might have missed the array_map()
function which is what you alluded to with your map { "$_=$hash{$_}" } keys %hash
example.
混沌的答案很简单。但是,对于更一般的意义,您可能忽略了array_map()函数,这是您在映射{“$_=$hash{$_}”}%hash示例中提到的。