如何使用PHP将数组分解为另一个数组而不是子数组?

时间:2014-10-19 14:17:19

标签: php arrays

是否有可能爆炸数组的值来创建具有这些值的新数组。我只能通过一个明确的步骤来做到这一点。

我有以下数组:

Array (
[0] => OtherMachines, Polymers
[1] => Engines/Pumps/Turbines, Measurement
[2] => Materials/Metallurgy
[3] => Materials/Metallurgy, ThermProcesses
)

然后我爆炸了它的价值观:

foreach ($array00 as $v) {
    $array01 = explode(", ", $v);
}

并收到以下数组:

Array
(
[0] => Array
    (
        [0] => OtherMachines
        [1] => Polymers
    )

[1] => Array
    (
        [0] => Engines/Pumps/Turbines
        [1] => Measurement
    )

[2] => Array
    (
        [0] => Materials/Metallurgy
    )

[3] => Array
    (
        [0] => Materials/Metallurgy
        [1] => ThermProcesses
    )
)

我必须压扁数组才能得到我想要的那个:

// Flatten the array.
$array02 = call_user_func_array('array_merge', $array01);

最终结果:

Array (
[0] => OtherMachines
[1] => Polymers
[2] => Engines/Pumps/Turbines
[3] => Measurement
[4] => Materials/Metallurgy
[5] => Materials/Metallurgy
[6] => ThermProcesses
)

有没有办法直接这样做?

非常感谢提前。

3 个答案:

答案 0 :(得分:2)

是的,只要内爆然后爆炸。

$result = explode(', ', implode(', ', $array));

答案 1 :(得分:1)

$arr = array (
    'OtherMachines, Polymers',
    'Engines/Pumps/Turbines, Measurement',
    'Materials/Metallurgy',
    'Materials/Metallurgy, ThermProcesses'
);

print_r(array_map('trim', explode(',', implode(',', $arr))));

Array
(
    [0] => OtherMachines
    [1] => Polymers
    [2] => Engines/Pumps/Turbines
    [3] => Measurement
    [4] => Materials/Metallurgy
    [5] => Materials/Metallurgy
    [6] => ThermProcesses
)

http://codepad.org/h0n6NU3V

答案 2 :(得分:0)

或者简单地说:

$arr = array (
    'OtherMachines, Polymers',
    'Engines/Pumps/Turbines, Measurement',
    'Materials/Metallurgy',
    'Materials/Metallurgy, ThermProcesses'
);

print_r(explode(', ', implode(', ', $arr)));