简体   繁体   English

如何内爆二维数组中的子数组?

[英]How to implode subarrays in a 2-dimensional array?

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() ?也许array_map() ...but then I would have to create another function. ...但是我将不得不创建另一个功能。

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.现在比较这两种解决方案并判断哪个更具可读性。

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;

You don't need to write/iterate a conditional statement if you type the strings (non-arrays) as single-element arrays before imploding them.如果在内爆之前将字符串(非数组)作为单元素数组type ,则不需要编写/迭代条件语句。

With array_map() : ( Demo )使用array_map() : (演示)

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

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

Or from PHP7.4, array_map() with arrow function syntax: ( Demo )或者从 PHP7.4 开始, array_map()带有箭头函数语法:( Demo )

var_export(
    array_map(fn($v) => implode(',', (array)$v), $my_array)
);

Or array_walk() and modification by reference ( Demo )或者array_walk()和引用修改( Demo

array_walk(
    $my_array,
    function(&$v) {
        $v = implode(',', (array)$v);
    }
);
var_export($my_array);

Or a foreach loop: ( Demo )或 foreach 循环:(演示

foreach ($my_array as &$v) {
    $v = implode(',', (array)$v);
}
var_export($my_array);

All snippets will output:所有片段将输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM