PHP:用逗号分隔文本

时间:2009-04-18 19:31:52

标签: php arrays

我有一个multidimensinal数组..例如:

Array (
    [0] => Array
        (
            [title] => Star Trek - Viaje a las estrellas
            [country] => Venezuela, Spain, long title, poster title
        )

    [1] => Array
        (
            [title] => Viaje a Las Estrellas
            [country] => Venezuela
        )
)

我希望从[country]的逗号之间获取文本,并将每个元素插入到单独的索引中,例如:

Array (
    [0] => Array
        (
            [title] => Star Trek - Viaje a las estrellas
            [country] => [0] => Venezuela
                         [1] => Spain
                         [2] => long title
                         [3] => poster title
        )

    [1] => Array
        (
            [title] => Viaje a Las Estrellas
            [country] => Venezuela
        )
)

可能阵列布局不正确但我只想向您解释我需要做什么。 请注意,并非[country]包含以逗号分隔的元素,有时只是一个元素。

我该怎么做?

谢谢!

3 个答案:

答案 0 :(得分:4)

尝试在country元素上使用explode()。您可以使用", "的分隔符,因为它们是以逗号分隔的值。

一种方法(与其他人的建议类似)将是:

// Assuming that $data contains your multidimensional array...
for ($i = 0; $i < count($data); $i++)
{
    if (strstr($data[$i]['country'], ', '))
    {
        $data[$i]['country'] = explode(', ', $data[$i]['country']);
    }
}

此外,请注意,您并不需要使用strpos() - strstr()在这里完美运作。

答案 1 :(得分:1)

您可以使用preg_split函数和正则表达式来拆分字符串:

foreach ($array as $key => $item) {
    if (strpos($item['country'], ',') !== false) {  // check if string contains a comma
        $array[$key]['country'] = preg_split('/,\s*/', $item['country']);
    }
}

答案 2 :(得分:0)

$a = Array (
    0 => Array
        (
            "title" => "Star Trek - Viaje a las estrellas",
            "country" => "Venezuela, Spain, long title, poster title"
        ),

    1 => Array
        (
            "title" => "Viaje a Las Estrellas",
            "country" => "Venezuela"
        )
);
$res = array();    
    foreach($a as $k => $v){
        foreach($v as $key => $value){
            switch($key){
                case "country":                                
                    $r = split(",", $value); 
                    foreach($r as $index => $val){
                        $res[$k][$key][$index] = trim($val);
                    }
                  break;
                default:
                    $res[$k][$key] = $value;
                break;
            }
        }
    }

    print_r($res);

输出:

Array
(
    [0] => Array
        (
            [title] => Star Trek - Viaje a las estrellas
            [country] => Array
                (
                    [0] => Venezuela
                    [1] => Spain
                    [2] => long title
                    [3] => poster title
                )
        )
    [1] => Array
        (
            [title] => Viaje a Las Estrellas
            [country] => Array
                (
                    [0] => Venezuela
                )
        )
)