如何内爆二维数组中的子数组? [英] 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:
我有以下数组:
$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?
我的意思是,如果值是单行代码中的数组,则将其内爆吗?也许array_map()
? ...但是然后我将不得不创建另一个函数.
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.
推荐答案
只需创建一个新数组并设置元素(-;
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;
这篇关于如何内爆二维数组中的子数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文