处理数组的内容

时间:2010-02-23 09:31:25

标签: php

我有一个以字符串形式保存的逗号分隔值列表:

blue, left-right-middle, panther.png

然后我有三个功能:

  1. 设置背景颜色

  2. 设置布局列的顺序

  3. 设置个人资料图片

  4. 目前我使用for each循环将值分解为单独的字符串,但我怎样才能更好地控制结果。

    E.g

    First result of array = Sets background colour
        Second result of array = Sets order of columns
        Third results of array = profile image
    

    我可以将数组的结果写成3个单独的变量,所以我可以将变量分配给每个函数吗?

    像这样:

        First result of array = $backgroundColour
        Second result of array = $orderColumns
        Third results of array = $profileImage
    

    我有什么想法可以解决这个问题吗?

7 个答案:

答案 0 :(得分:5)

从PHP5.3起,您可以使用str_getcsv()将CSV字符串解析为数组 另外,请查看list以将变量分配为数组。

list( $color, $order, $image ) = str_getcsv($csvString);

在PHP5.3之前,您使用explode代替str_getcsv。请参阅下面的@poke示例。

str_getcsv优于explode的优势在于您可以将分隔符附件转义字符指定为让你更好地控制结果。

str_getcsv非常聪明,可以自动修剪空白。列出的值将包含

string(4) "blue", string(17) "left-right-middle", string(11) "panther.png"`

但是,增加控制会降低成本。对于给定的示例字符串,explode基本上(在我的机器上约为6到8次)。

答案 1 :(得分:4)

使用list

$line = 'blue, left-right-middle, panther.png';
list( $bkgColor, $columnOrder, $profileImage ) = explode( ', ', $line );

echo 'Background color: ' . $bkgColor . "<br />\n";
echo 'Column order: ' . $columnOrder. "<br />\n";
echo 'Profile image: ' . $profileImage . "<br />\n";

答案 2 :(得分:1)

您可以使用explodelist

$string = 'blue, left-right-middle, panther.png';
list($backgroundColour, $orderColumns, $profileImage) = explode(', ', $string);

答案 3 :(得分:0)

$array = explode(', ', 'blue, left-right-middle, panther.png');
list($color, $position, $image) = $array;
echo $color; // blue
echo $position; //left-right-middle
echo $image; //panther.png

答案 4 :(得分:0)

可以使用php的str_getcsv函数。

请参阅手册:http://www.php.net/manual/en/function.str-getcsv.php

答案 5 :(得分:0)

使用以下代码。

$ string ='blue,left-right-middle,panther.png';

list($ color,$ position,$ image)= split(',',$ string);

echo'背景颜色:'。 $ color。“
\ n”;

echo'列顺序:'。 $现在的位置。 “
\ n” 个;

echo'Profile image:'。 $ image。 “
\ n” 个

答案 6 :(得分:0)

为了与众不同,您可以使用sscanf

$string = 'blue, left-right-middle, panther.png';

sscanf( $string, '%s, %s, %s', $backgroundColour, $orderColumns, $profileImage );
相关问题