How to implode subarrays in a 2-dimensional array?

ぃ、小莉子 提交于 2019-11-27 07:27:32

问题


I want to implode values in to a comma-separated string if they are an array:

I have the following array:

$my_array = [
    "keywords" => "test",
    "locationId" => [ 0 => "1", 1 => "2"],
    "industries" => "1"
];

To achieve this I have the following code:

foreach ($my_array as &$value)
    is_array($value) ? $value = implode(",", $value) : $value;
unset($value);

The above will also change the original array. Is there a more elegant way to create a new array that does the same as the above?

I mean, implode values if they are an array in a single line of code? perhaps array_map()? ...but then I would have to create another function.


回答1:


Just create a new array and set the elements (-;

<?php
...
$new_array = [];
foreach ($my_array as $key => $value)
     $new_array[$key] = is_array($value) ? implode(",", $value) : $value;



回答2:


Just append values to new array:

$my_array = [
   "keywords" => "test",
   "locationId" => [ 0 => "1", 1 => "2"],
   "industries" => "1",
];
$new_Array = [];
foreach ($my_array as $value) {
    $new_Array[] = is_array($value) ? implode(",", $value) : $value;
}
print_r($new_Array);

And something that can be called a "one-liner"

$new_Array = array_reduce($my_array, function($t, $v) { $t[] = is_array($v) ? implode(",", $v) : $v; return $t; }, []);

Now compare both solutions and tell which is more readable.




回答3:


You don't need to write/iterate a conditional statement if you type the strings (non-arrays) as single-element arrays before imploding them.

Code: (Demo)

$my_array = [
    "keywords" => "test",
    "locationId" => [ 0 => "1", 1 => "2"],
    "industries" => "1"
];

var_export(array_map(function($v){return implode(',',(array)$v);},$my_array));

Output:

array (
  'keywords' => 'test',
  'locationId' => '1,2',
  'industries' => '1',
)

Or if you prefer a foreach loop, this will provide the same result:

foreach($my_array as $k=>$v){
    $result[$k]=implode(',',(array)$v);
}
var_export($result);


来源:https://stackoverflow.com/questions/45253716/how-to-implode-subarrays-in-a-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!