How to combine the keys and values of an array in PHP

前端 未结 4 1655
北海茫月
北海茫月 2021-01-17 22:25

Say I have an array of key/value pairs in PHP:

array( \'foo\' => \'bar\', \'baz\' => \'qux\' );

What\'s the simplest way to transform

相关标签:
4条回答
  • 2021-01-17 22:27

    A "curious" way to do it =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, '', '::' ) ) );
    
    0 讨论(0)
  • 2021-01-17 22:39

    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!).

    "Oh, but on array_map()you only get the value!".

    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));
    
    0 讨论(0)
  • 2021-01-17 22:40

    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.

    0 讨论(0)
  • 2021-01-17 22:41
    function parameterize_array($array) {
        $out = array();
        foreach($array as $key => $value)
            $out[] = "$key=$value";
        return $out;
    }
    
    0 讨论(0)
提交回复
热议问题