Php 处理数组的内容
我有一个逗号分隔的值列表,作为字符串保存:Php 处理数组的内容,php,Php,我有一个逗号分隔的值列表,作为字符串保存: blue, left-right-middle, panther.png 然后我有三个功能: 设置背景色 设置布局的列顺序 设置配置文件图像 目前,我对每个循环使用一个,将值分解成单独的字符串,但是如何更好地控制结果呢 例如 我是否可以将数组的结果写入3个单独的变量中,以便将变量分配给每个函数 像这样: First result of array = $backgroundColour Second result of array =
blue, left-right-middle, panther.png
然后我有三个功能:
,将值分解成单独的字符串,但是如何更好地控制结果呢
例如
我是否可以将数组的结果写入3个单独的变量中,以便将变量分配给每个函数
像这样:
First result of array = $backgroundColour
Second result of array = $orderColumns
Third results of array = $profileImage
有什么想法吗?从PHP5.3开始,您可以使用它将CSV字符串解析为数组。
另外,请看一下如何将变量当作数组来分配
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"`
然而,增加的控制会降低速度<对于给定的示例字符串,“代码>爆炸”(code>explode)
大大加快了速度(在我的机器上大约是6到8倍)。使用:
$line='blue,左-右-中,panther.png';
列表($bkgColor、$columnOrder、$profileImage)=分解(',',$line);
回显“背景色:”$bkgColor。“
\n”;
回显“列顺序:”$专栏顺序。“
\n”;
回显“配置文件图像:”$档案图像。“
\n”;
您可以使用和:
请使用php的str_getcsv函数
请参见手册中的:使用以下代码 $string='blue,左-右-中,panther.png' 列表($color、$position、$image)=拆分(“,”,$string) 回显“背景色:”$颜色。“
\n” 回显“列顺序:”$职位。“
\n”
回显“配置文件图像:”$形象。“
\n”为了与众不同,您可以使用
你真的那么讨厌索引吗?!但是,如果字符串的格式与上面的格式完全相同(使用“
”,“
作为分隔符),str_getcsv
将不起作用,因为分隔符只要求是一个字符(在本例中,您也不需要enclosure或escape,因为这些字符串的可能值非常有限)。
string(4) "blue", string(17) "left-right-middle", string(11) "panther.png"`
$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";
$string = 'blue, left-right-middle, panther.png';
list($backgroundColour, $orderColumns, $profileImage) = explode(', ', $string);
$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
$string = 'blue, left-right-middle, panther.png';
sscanf( $string, '%s, %s, %s', $backgroundColour, $orderColumns, $profileImage );