Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...