Imploding an associative array in PHP

后端 未结 7 800
攒了一身酷
攒了一身酷 2020-12-08 19:44

Say I have an array:

$array = Array(
  \'foo\' => 5,
  \'bar\' => 12,
  \'baz\' => 8
);

And I\'d like to print a line of text in m

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 20:28

    Taking help from the answer of @linepogl, I edited the code to make it more simple, and it works fine.

    function array_map_assoc($array){
      $r = array();
      foreach ($array as $key=>$value)
        $r[$key] = "$key ($value)";
      return $r;
    }
    

    And then, just call the function using

    echo implode(' , ', array_map_assoc($array));
    

提交回复
热议问题