开发者

Imploding an associative array in PHP

Say I have an array:

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

And I'd like to print a line of text in my view like this:

"The values are: foo (5), bar (12), baz (8)"

What I could do is this:

$list = Array();
foreach ($array as $key => $value) {
  $list[] = "$key ($value)";
}
echo 'The values are: '.implode(', ',$list);

But I feel like there should be an easier way, without having to create th开发者_运维技巧e $list array as an extra step. I've been trying array_map and array_walk, but no success.

So my question is: what's the best and shortest way of doing this?


For me the best and simplest solution is this:

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

http_build_query (php.net)


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));


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.


You could print out the values as you iterate:

echo 'The values are: ';
foreach ($array as $key => $value) {
  $result .= "$key ($value),";
}
echo rtrim($result,',');


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));


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)


I came up with

    foreach ($array as &$item)
    {
        $item = reset($item);
    }
    $array = implode(', ', $array);
    var_dump($array);


I do it this way :

  • I firstly define a new array to fill with the values of my existing array
  • I check if my associative array is set and is not empty
  • Then loop on my array and fill the new one with the values
  • After the loop has terminated, i implode the new array

as you can see :

$new_array = [];

if (isset($array) && $array != null) {
    foreach ($array as $el) {$new_array[] = $el->value;}
    $new_array = implode(',', $new_array);
}

echo $new_array;


echo json_encode($array); if it isn't a valid array it will return null.


Loop throw the array and put , expect the end of loop.

$index = 0; // index
$len = count($array); // Length of the array

// Loop throw the array
foreach($array as $key => $a) {
   echo "$key ($a)" . ($index != $len - 1 ? ',' : '');
   $index++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜