数组格式看起来不正确

时间:2014-07-25 06:20:08

标签: php arrays

在下面的代码中,我拆开了一个CSS文件并试图返回一个数组。它正在工作,但我的格式看起来很奇怪。我做错了什么?

我正在寻找的样本:

Array
(
    [body] => Array
        (
            [width] => 100%
            [background-color] => #e6e6e6
        )
)

我的代码:

$file = file_get_contents($_SERVER['DOCUMENT_ROOT'] . '../parse-css-upload/' . $this->newFileName);

$element = explode('}', $file);

$css_array = array(); // master array to hold all values
$element = explode('}', $file);

foreach ($element as $element) {
    // get the name of the CSS element
    $a_name = explode('{', $element);
    $name = $a_name[0];

    // get all the key:value pair styles
    $a_styles = explode(';', $element);

    // remove element name from first property element
    $a_styles[0] = str_replace($name . '{', '', $a_styles[0]);

    // loop through each style and split apart the key from the value
    $count = count($a_styles);
    for ($a=0;$a<=$count;$a++) {
        if ($a_styles[$a] != '') {
            $a_key_value = explode(':', $a_styles[$a]);
            // build the master css array
            $css_array[$name][$a_key_value[0]] = $a_key_value[1];
        }
    }               
}

实际出局:

Array
(
    [body, html ] => Array
        (
            [
    width] =>  100%
            [
    background-color] =>  #e6e6e6
            [  
] => 
        )

    [


body ] => Array
        (
            [
    font-family] =>  "Open Sans", sans-serif
            [
    color] =>  #686868
            [
    font-size] =>  16px
            [
    font-weight] =>  300
            [
    line-height] =>  1.7
            [
] => 
        )

2 个答案:

答案 0 :(得分:1)

尝试:

$css_array[$name][trim($a_key_value[0])] = trim($a_key_value[1]);

你周围有新的换行符。

答案 1 :(得分:1)

试试希望这会有所帮助

for ($a=0;$a<=$count;$a++) {
    if (trim($a_styles[$a]) != '') {
        $a_key_value = explode(':', $a_styles[$a]);
        // build the master css array
        $css_array[trim($name)][trim($a_key_value[0])] = trim($a_key_value[1]);
    }
} 

在代码中使用trim