Imploding an associative array in PHP

后端 未结 7 764
攒了一身酷
攒了一身酷 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:16

    For me the best and simplest solution is this:

    $string = http_build_query($array, '', ',');
    

    http_build_query (php.net)

    0 讨论(0)
  • 2020-12-08 20:21

    The problem with array_map is that the callback function does not accept the key as an argument. You could write your own function to fill the gap here:

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

    Now you can do that:

    echo implode(',',array_map_assoc(function($k,$v){return "$k ($v)";},$array));
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-08 20:32

    Clearly, the solution proposed by Roberto Santana its the most usefull. Only one appointmen, if you want to use it for parse html attributes (for example data), you need double quotation. This is an approach:

    Example: var_dump( '<td data-'.urldecode( http_build_query( ['value1'=>'"1"','value2'=>'2' ], '', ' data-' ) ).'></td>');
    
    Output: string '<td data-value1="1" data-value2=2></td>' (length=39)
    
    0 讨论(0)
  • 2020-12-08 20:35

    There is a way, but it's pretty verbose (and possibly less efficient):

    <?php
    $array = Array(
      'foo' => 5,
      'bar' => 12,
      'baz' => 8
    );
    
    // pre-5.3:
    echo 'The values are: '. implode(', ', array_map(
       create_function('$k,$v', 'return "$k ($v)";'),
       array_keys($array),
       array_values($array)
    ));
    
    echo "\n";
    
    // 5.3:
    echo 'The values are: '. implode(', ', array_map(
       function ($k, $v) { return "$k ($v)"; },
       array_keys($array),
       array_values($array)
    ));
    ?>
    

    Your original code looks fine to me.

    0 讨论(0)
  • 2020-12-08 20:37

    You could print out the values as you iterate:

    echo 'The values are: ';
    foreach ($array as $key => $value) {
      $result .= "$key ($value),";
    }
    echo rtrim($result,',');
    
    0 讨论(0)
提交回复
热议问题