代码之家  ›  专栏  ›  技术社区  ›  thecore7

PHP分解数组,带有2种分隔符

  •  0
  • thecore7  · 技术社区  · 12 年前

    我有这个选项数组:

    string(111) "colors:black;white;transparent;pink;"    
    

    我如何将其分解,以便将其作为标签第一分隔符:并将数组中的其他分隔符作为选项?到目前为止,我有这一点:

    $options= explode(";",$rows[0]);
    $htm= '<ul class="product_opts">'.$lang['available_options'].'';
    foreach ($options as $value) { 
            $row=mysql_fetch_row($result);
                $htm.='<li style="text-align:left;font-weight:normal;">'.$value.'</li>';
                }
            $htm.= '</ul>';
            }
        echo $htm;    
    

    但它也将标签作为选项返回。。

    5 回复  |  直到 12 年前
        1
  •  2
  •   Mark Baker    12 年前
    $attributes="colors:black;white;transparent;pink;";
    
    list($attribute, $values) = array_map(
        function($value) {
            return array_filter(explode(';', $value));
        },
        explode(':', $attributes)
    );
    var_dump($attribute);
    var_dump($values);
    
        2
  •  1
  •   enterx    12 年前
    $str = "colors:black;white;transparent;pink;";
    
    list($label, $optionsStr) = explode(":", $str);
    
    $optionsStr = rtrim($optionsStr, ";");
    $options = explode(";", $optionsStr);
    
    echo "<pre>";
    print_r($label);
    
    print_r($options);
    
        3
  •  1
  •   Flosi    12 年前
    1. 按以下方式分解字符串 : 。第一个标记将是您的标签,第二个标记是您的选项。
    2. 将第二个标记分解为 ; ,您可以在阵列中选择。
        4
  •  1
  •   Nouphal.M    12 年前

    尝试

    $str = "colors:black;white;transparent;pink;";
    $arr = explode(";",$str);
    $key = explode(":",$arr[0]);
    $arr[0] = $key[1];
    unset($arr[sizeof($arr)-1]);
    

    参见演示 here

        5
  •  0
  •   Karthick Kumar    12 年前

    使用 split 这样做

    $options= split("[;|:]",$rows[0]);