简体   繁体   English

PHP用逗号分隔的数组值构建数组

[英]Php build array from comma separated array values

I have a array with some array values contains multiple values separated by comma as shown below. 我有一个数组,其中一些数组值包含多个用逗号分隔的值,如下所示。

$a  =  array(
              '0' => 't1,t2',
              '1' => 't3',
              '2' => 't4,t5'
           );

I need output in the following format. 我需要以下格式的输出。

Array
    (
        [0] => t1
        [1] => t2
        [2] => t3
        [3] => t4
        [4] => t5
    )

This is how tried and getting the results. 这是如何尝试并获得结果的方法。 Is there any other alternative way without looping twice. 有没有其他其他方法,而无需循环两次。

$arr_output = array();

    foreach($a as $val)
    {
        $temp = explode(',', $val);
        foreach($temp as $v)
        {
            $arr_output[] = $v;
        }
    }

Thanks. 谢谢。

$array = Array (
        "t1,t2",
        "t3",
        "t4,t5"
    );

$splitted = array_map (function ($a) {return explode (",", $a);}, $array);
$arr = array_reduce($splitted, function ($a, $b) {
     return array_merge($a, (array) $b);
}, []);    

print_r ($arr);

First of all, you split every string by coma. 首先,您用逗号分隔每个字符串。 You get an array of arrays. 您将得到一个数组数组。 To merge them, you call a merging function, such as the one in the example with array_reduce. 要合并它们,请调用合并函数,例如本示例中的array_reduce函数。

First convert your old array in to string like, 首先将您的旧数组转换为字符串,
$old_array = array ( "t1,t2", "t3", "t4,t5" );
to
$string = implode(",", $old_array);
Now 现在
echo $string;
gives a string with coma separator now using this you get desired array 给出一个带有逗号分隔符的字符串,现在使用此字符串可以获得所需的数组

$new_array = explode(",", $string);

If you print this you will get 如果您打印此,您将得到

Array(
[0] => t1
[1] => t2
[2] => t3
[3] => t4
[4] => t5)

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

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