将样式数组转换为常规CSS

时间:2013-03-05 10:44:03

标签: php css

我有一个包含所有样式的数组,我必须通过在PHP中循环将它们更改为正确的CSS。

例如,

Array
(
    [#outlook a] => Array
        (
            [padding] => Array
                (
                    [0] => 0
                )

        )

    [body] => Array
        (
            [width] => Array
                (
                    [0] => 100% !important
                )

            [-webkit-text-size-adjust] => Array
                (
                    [0] => none
                )

            [margin] => Array
                (
                    [0] => 0
                )

            [padding] => Array
                (
                    [0] => 0
                )

            [background-color] => Array
                (
                    [0] => #FAFAFA
                )

        )
[.preheaderContent div a] => Array
    (
        [color] => Array
            (
                [0] => #336699
            )

        [font-weight] => Array
            (
                [0] => normal
            )

        [text-decoration] => Array
            (
                [0] => underline
            )

    )

[.preheaderContent div a:visited] => Array
    (
        [color] => Array
            (
                [0] => #336699
            )

        [font-weight] => Array
            (
                [0] => normal
            )

        [text-decoration] => Array
            (
                [0] => underline
            )

    )

)

像这样我会有一个包含所有样式信息的大数组。所以我必须将其转换为适当的CSS。我知道这很简单。但我在递归循环的某个地方失败了。这是我对此的功能。

function cssbuild(&$cssArray)
{
    foreach ($cssArray as $selector => $style) 
    {
        if(is_array($style))
        {
            return $this->cssbuild($style);
        }
        else
        {
            $cssArray[$selector] = $cssArray[$selector].":".$style.";";
        }
    }
}

非常感谢任何关于如何做到这一点的想法......

2 个答案:

答案 0 :(得分:2)

试试这个:

function createCSS($cssArray)
{
    $css = '';
    foreach ($cssArray as $classname => $properties)
    {
        $css .= "$classname{";
        foreach( (array) $properties as $propertyname => $propertyvalue )
        $css .= $propertyname .": ".$propertyvalue[0].";";
        $css .= "}";
    }
    return $css;
}

答案 1 :(得分:0)

在给定的示例中没有递归...

您可以使用此功能进行递归

<?php
BuildList($arrayParent, 0);

function BuildList($arrayElements, $depth)
{
    foreach($arrayElements as $element => $style)
    {
        echo str_repeat("&nbsp;&nbsp;", $depth) . $element . ":" . $style;
        $depth++;
        if(count($element->subCSSElement) > 0)
            $depth = BuildList($element->subCSSElement, $depth);

        return $depth;
    }
}
?>