-2

如何将带有管道的逗号分隔字符串转换为两个不同的数组?

$combo_string = 'blue|car, red|truck, green|boat, yellow|bike';

我需要的地方:

$colors_array = 

Array (
[0] => blue
[1] => red
[2] => green
[3] => yellow
)

$vehicles_array = 

Array (
[0] => car
[1] => truck
[2] => boat
[3] => bike
)

提前致谢。

4

2 回答 2

2
$combo_array = explode(', ', $combo_string);

$colors_array = $vehicles_array = array();
foreach ($combo_array as $piece) {
   list($color, $vehicle) = explode('|', $piece);
   $colors_array[] = $color;
   $vehicles_array[] = $vehicle;
}
于 2012-12-20T21:59:59.150 回答
1

我没有测试以下内容,但它应该大致正确:

$combo_string = 'blue|car, red|truck, green|boat, yellow|bike';

$initial_array = explode(", " $combo_string);

$vehicles_array = array();
$colors_array = array();

foreach ($combo_string as $item)
{
  $seperate_colour = explode("|", $item);

  $colors_array[] = $seperate_colour[0];
  $vehicles_array[] = $seperate_colour[1];

}
于 2012-12-20T22:03:37.207 回答