dourui9570 2013-09-25 07:29
浏览 58
已采纳

根据选择器和声明显示数据库中的CSS(key => value)

I'm storing basic CSS settings in a database so they can be configurable by a client using some sort of web form, then these can be echoed out within the style tag and override any existing settings. Basic settings like font family, background color, font color etc.

Table:

CSS settings stored in table

Rather than setting a column name for every css selector, I have decided to store settings like shown above as this would be easier to update and maintain.

I am trying to echo the "style_name" followed by "{", then every "style_value" then a closing tag "}". I'm nearly there, but I'm trying to figure out how to know when all style values associated with the style name have been echoed, then echo a closing tag, rather than after every value.

PHP Code:

$sql = 'SELECT style_name, style_value FROM style ORDER BY style_name';
$results = $stmt->fetchAll(PDO::FETCH_OBJ);

$unique_css = array();

foreach ($results as $css) {
    if (!in_array($css->style_name, $unique_css))  {
        $unique_css[] = $css->style_name;
        echo $css->style_name . " { " . $css->style_value;
    } else {
        echo $css->style_value;
    }
    echo '}';
}

Returns:

body {
    background: #CCC; }
    font-family: 'Verdana', sans-serif; }
    font-size: 40px; }
    text-align:center;
}

h1 {
    font-size: 50px;
}

h2 {
    font-family: 'Arial', sans-serif;
}

I understand that I could just echo every style name with value e.g.:

body { value1 } body {value2}

But I think that is just messy IMO. Help appreciated!

  • 写回答

6条回答 默认 最新

  • dongtao4890 2013-09-25 07:52
    关注

    One of the best solutions is to use proper MySQL to group by the style names by using the GROUP_BY keyword and concatenating the style value string with GROUP_CONCAT:

    SELECT style_name, GROUP_CONCAT(style_value SEPARATOR ' ') style_values FROM style GROUP BY style_name
    

    This will result in:

    STYLE_NAME  STYLE_VALUES
    body        background: #CCC; font-family: 'Verdana', sans-serif; font-size: 40px; text-align: center;
    h1          font-size: 50px;
    h2          font-family: 'Arial', sans-serif;
    

    Example fiddle:

    DEMO

    More information about GROUP_BY and GROUP_CONCAT: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

    After that you can put all styles together in a simple manner:

    foreach ($results as $css) {
        echo $css->style_name . " { " . $css->style_values + " }";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度