处理数组的内容

CLi*_*own 2 php

我有一个逗号分隔的值列表作为字符串保存:

blue, left-right-middle, panther.png
Run Code Online (Sandbox Code Playgroud)

然后我有三个功能:

  1. 设置背景颜色

  2. 设置布局的列顺序

  3. 设置个人资料图片

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

例如

First result of array = Sets background colour
    Second result of array = Sets order of columns
    Third results of array = profile image
Run Code Online (Sandbox Code Playgroud)

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

像这样:

    First result of array = $backgroundColour
    Second result of array = $orderColumns
    Third results of array = $profileImage
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*don 5

从PHP5.3开始,您可以使用str_getcsv()将CSV字符串解析为数组.
另外,看看list如何将变量分配为数组.

list( $color, $order, $image ) = str_getcsv($csvString);
Run Code Online (Sandbox Code Playgroud)

在PHP5.3之前,您将使用explode而不是str_getcsv.请参阅下面的@poke示例.

str_getcsv超过的优点explode是您可以指定分隔符,机箱转义字符,以便您更好地控制结果.

str_getcsv足够智能自动修剪空白.列出的值将包含

string(4) "blue", string(17) "left-right-middle", string(11) "panther.png"`
Run Code Online (Sandbox Code Playgroud)

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