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

前端 未结 4 1677
北海茫月
北海茫月 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: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));
    

提交回复
热议问题