Home Backend Development PHP Tutorial How to convert nested PHP arrays to CSS rules? (code example)

How to convert nested PHP arrays to CSS rules? (code example)

Mar 18, 2019 pm 03:55 PM
php array

Many aspects of the application can be automated, for example we can use some PHP code (such as using arrays) to generate style sheets. So how to achieve it? The following article will show you how to convert nested PHP arrays into CSS rules and display them in the form of strings. I hope it will be helpful to you.

How to convert nested PHP arrays to CSS rules? (code example)

Let’s take a look at how to convert nested associative arrays into CSS characters.

1. Write a function to convert an associative array into a CSS string

To convert an array into a CSS string in PHP (in SASS or LESS case using rules or simple variables) we will use the following function:

<?php
/**
 * @param array $rules
 *   CSS规则的数组形式为:
 *   array(&#39;selector&#39;=>array(&#39;property&#39; => &#39;value&#39;)). 
 *   还支持选择器
 *   嵌套示例:
 *   array(&#39;selector&#39; => array(&#39;selector&#39;=>array(&#39;property&#39; => &#39;value&#39;))).
 *
 * @return 字符串一个CSS规则字符串。它不包含在<style>标签中。
 */
function css_array_to_css($rules, $indent = 0) {
    $css = &#39;&#39;;
    $prefix = str_repeat(&#39;  &#39;, $indent);
    foreach ($rules as $key => $value) {
        if (is_array($value)) {
            $selector = $key;
            $properties = $value;
            $css .= $prefix . "$selector {\n";
            $css .= $prefix . css_array_to_css($properties, $indent + 1);
            $css .= $prefix . "}\n";
        } else {
            $property = $key;
            $css .= $prefix . "$property: $value;\n";
        }
    }
    return $css;
}
//调用css_array_to_css()函数转换
//code
?>
Copy after login

Description: This function basically expects as first argument an array containing CSS rules or simple properties, which is not an array Each key => value; will be represented as key : value;, and if the value of the key is an array, the rule for css will be introduced.

2. Use the function

As mentioned in the above function description, it returns a CSS character from an array with specified rules string. This function works fine with pure CSS rules, media queries, SASS and LESS as long as the structure of the array is valid. For example:

● Convert to CSS:

Add the following code after the css_array_to_css() function:

$stylesheet = array(
    "body" => array(
        "margin" => "0",
        "font-size" => "1rem",
        "font-weight" => 400,
        "line-height" => 1.5,
        "color" => "#212529",
        "text-align" => "left",
        "background-color" => "#fff"
    ),
    ".form-control" => array(
        "display" => "block",
        "width" => "100%!important",
        "font-size" => "1em",
        "background-color" => "#fff",
        "border-radius" => ".25rem"
    )
);
echo(css_array_to_css($stylesheet));
Copy after login

The previous code snippet will output the following CSS Rules:

body {
  margin: 0;
  font-size: 1rem;
  font-weight: 400;
  line-height: 1.5;
  color: #212529;
  text-align: left;
  background-color: #fff;
}
.form-control {
  display: block;
  width: 100%!important;
  font-size: 1em;
  background-color: #fff;
  border-radius: .25rem;
}
Copy after login

● Conversion to SASS/SCSS:

Due to the recursive implementation, it will be possible to nest multiple rules within a rule, which allows us to generate valid Syntax:

$sass = array(
    "nav" => array(
        "ul" => array(
            "margin" => 0,
            "padding" => 0,
            "list-style" => "none"
        ),
        "li" => array(
            "display" => "inline-block"
        ),
        "a" => array(
            "display" => "block",
            "padding" => "6px 12px",
            "text-decoration" => "none"
        )
    )
);
echo css_array_to_css($sass);
Copy after login

The previous snippet will output the following SASS code:

nav {
  ul {
      margin: 0;
      padding: 0;
      list-style: none;
  }
  li {
      display: inline-block;
  }
  a {
      display: block;
      padding: 6px 12px;
      text-decoration: none;
  }
}
Copy after login

● Convert to LESS:

Works the same as SASS , we can also use LESS to write complex rules:

$less = array(
    "@nice-blue" => "#5B83AD",
    "@light-blue" => "@nice-blue + #111",
    "#header" => array(
        "color" => "@light-blue"
    ),
    ".component" => array(
        "width" => "300px",
        "@media (min-width: 768px)" => array(
            "width" => "600px",
            "@media (min-resolution: 192dpi)" => array(
                "background-image" => "url(/img/retina2x.png)"
            )
        ),
        "@media (min-width: 1280px)" => array(
            "width" => "800px"
        )
    )
);
echo css_array_to_css($less);
Copy after login

The previous code segment will output the following LESS code:

@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;
#header {
  color: @light-blue;
}
.component {
  width: 300px;
  @media (min-width: 768px) {
    width: 600px;
    @media (min-resolution: 192dpi) {
          background-image: url(/img/retina2x.png);
    }
  }
  @media (min-width: 1280px) {
      width: 800px;
  }
}
Copy after login

Related video tutorial recommendations: "PHP Tutorial"

The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to convert nested PHP arrays to CSS rules? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP arrays to generate and display charts and statistical graphs How to use PHP arrays to generate and display charts and statistical graphs Jul 15, 2023 pm 12:24 PM

How to use PHP arrays to generate and display charts and statistical graphs. PHP is a widely used server-side scripting language with powerful data processing and graphic generation capabilities. In web development, we often need to display charts and statistical graphs of data. Through PHP arrays, we can easily implement these functions. This article will introduce how to use PHP arrays to generate and display charts and statistical graphs, and provide relevant code examples. Introducing the necessary library files and style sheets Before starting, we need to introduce some necessary library files into the PHP file

How to use PHP arrays to generate dynamic slideshows and image displays How to use PHP arrays to generate dynamic slideshows and image displays Jul 15, 2023 pm 01:17 PM

How to use PHP arrays to generate dynamic slideshows and picture displays. Slideshows and picture displays are common functions in web design and are often used in scenarios such as carousels and gallery displays. As a popular server-side scripting language, PHP has the ability to process data and generate dynamic HTML pages, and is very suitable for generating dynamic slideshows and picture displays. This article will introduce how to use PHP arrays to generate dynamic slideshows and picture displays, and give corresponding code examples. Prepare image data First, we need to prepare a set of image path data

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

What are the functions for averaging arrays in php? What are the functions for averaging arrays in php? Jul 17, 2023 pm 04:03 PM

PHP array averaging functions include: 1. array_sum(), which is used to calculate the sum of all values ​​in the array. In order to calculate the average, you can add all the values ​​in the array and then divide by the number of array elements; 2 , array_reduce(), used to iterate the array and calculate each value with an initial value; 3. array_mean(), used to return the average of the array, first calculate the sum of the array, and calculate the number of array elements, then The sum is divided by the number of array elements to get the average.

Effective implementation of array union in PHP Effective implementation of array union in PHP Apr 30, 2024 pm 01:03 PM

An effective way to implement array union in PHP: use the array_merge() function to merge multiple arrays, but not merge duplicate values. Combine array_unique() and array_merge() to merge arrays and keep duplicate values. Create a custom function to merge arrays based on specific requirements, such as merging sorted arrays.

See all articles