Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP foreach to build stylesheet

Tags:

foreach

php

Okay - so I'm creating a dynamic CSS stylesheet, which I want to set up with an array.

First let me say that I'm not a PHP expert, but I somewhat know my way around it.

Here's my very basic array.

$visual_css = array (
    array(
        "selector"  => "body",
        "property"  => "background",
        "value"     => "#FFF",
        "property2" => "color",
        "value2"    => "#000",
        "type"      => "css"
    )
);

So we have a selector, and two properties with values.

I now want to create the stylesheet, but I'm running into problems due to my lack of PHP knowledge.

foreach ($visual_css as $value) {
    switch ($value['type']) {
        case "css":

            // Open selector
            echo ( !empty($value['selector']) ? $value['selector'] . '{' : null );

            foreach ($value as $key => $item) {
                foreach ($value as $key2 => $item2) {
                    //Match only the id's against the key
                    if (preg_match('/^property/i', $key) && preg_match('/^value/i', $key2)) {
                        // First property
                        echo ( !empty($item) ? $item . ':' : null );
                            echo ( !empty($item2) ? $item2 . ';' : null );
                    }
                }

            }

            // Close selector
            echo ( !empty($value['selector']) ? '}' : null );

        break;
    }
}

Now I know this code isn't correct, as it's outputting the following in the stylesheet:

body{background:#FFF;background:#000;color:#FFF;color:#000;}

This is the desired result:

body{background:#FFF;color:#000;}

So basically, I want to be able to create an unlimited number of properties and values with an incrementing number after them, and have the code write it out.

Can anyone help me?

Thanks!

like image 760
thomasusborne Avatar asked Dec 21 '25 10:12

thomasusborne


2 Answers

So my approach uses a multidimensional array instead of a flat array to nest properties of selectors in sub-arrays. This way your approach is much more concise by first looping through the first layer, and then going through the children of each parent and composing the CSS for each property / value pair. It also makes iteration a cinch as opposed to having to inspect the values of keys to locate which pair you're at. If you need a different output format, your iteration code can decide that, and it should be left out of the structure

$visual_css = array (
    'body'  => array(
        'background'    => '#FFF',
        'color'         => '#000'
    )
);

$output = '';
foreach($visual_css as $k => $properties) {
    if(!count($properties))
        continue;

    $temporary_output = $k . ' {';

    $elements_added = 0;

    foreach($properties as $p => $v) {
        if(empty($v))
            continue;

        $elements_added++;

        $temporary_output .= $p . ': ' . $v . '; ';
    }

    $temporary_output .= "}\n";

    if($elements_added > 0)
        $output .= $temporary_output;
}

echo $output;
// body {background: #FFF; color: #000; }
like image 64
Bryan Avatar answered Dec 23 '25 23:12

Bryan


In your example you are looping over the same array twice, in this piece of code:

foreach ($value as $key => $item) {
    foreach ($value as $key2 => $item2) {

If you structured your data in a more logical way, you could make a cleaner loop code, too. I'd suggest you to structure the array with each property&value as a separate sub-array, for example:

$visual_css = array(
    array(
        'selector' => 'body',
        'properties' => array(
            'background' => '#fff',
            'color' => '#000'
        )
    )
    // ... etc ...
);

And then you can easily loop through it like this:

foreach ($visual_css as $selector)
{
    echo $selector['selector'].' { ';
    foreach ($selector['properties'] as $name => $value)
    {
        echo $name.': '.$value.'; ';
    }
    echo ' } ';
}
like image 23
pilsetnieks Avatar answered Dec 23 '25 23:12

pilsetnieks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!