Convert String Json CSS Inline to an array or json with PHP

0

I have a database in json and inside it there is a style object in which it has an inline css code, such as:

"padding: 90px 0px 20px 0px; background: # 000000; display: block;"

Let's say the return would be:

{
"style" : "padding: 90px 0px 20px 0px; background: #000000; display: block;"
}

And I need to get each parameter and turn it into an array where it would look something like this, generating an array or Json (I do not know what the best solution is), here's an example of what I want:

{
"padding" : "90px 0px 20px 0px",
"background" : "#000000",
"display" : "block"
}

I'm going to get this result and irrigate an input for each key, generating a form so that the user can change the values.

The closest I could get was with this:

$wrapStyle = "padding: 90px 0px 20px 0px; background: #000000; display: block;";
$bringStyleString = array_filter(explode(";", json_encode($wrapStyle)));
$bringStyleString = array_filter(explode(";", json_encode($wrapStyle)));
$br = json_decode(json_encode(array_filter(explode(";",$wrapStyle))));
$tks = array();

foreach ($br as $key => $value) {

    $t = explode(":", $value);
    $tk = $t[1];

    $tk1 = array(trim($t[0]));
    $tk2 = array(trim($t[1]));

    $tk = json_decode(json_encode($tk));
    $tks[] = array_combine($tk1, $tk2);

}

$contagem = count($tks);

print_r($tks);

This is generating an array and within it other arrays, I would like to leave all the returns inside an array just like for example being the return:

Array ([padding] => 90px 0px 20px 0px, [background] = > # 000000, [display] = > block)

Would that be the way? Or rather follow a totally different one?

    
asked by anonymous 02.06.2017 / 16:32

1 answer

1

You can use array_reduce to generate it at one time, follow an example

$wrapStyle = "padding: 90px 0px 20px 0px; background: #000000; display: block;";

$explode = explode(';',$wrapStyle);

$styles = array_reduce($explode,function($carry,$item){
    if(empty($item))return $carry;
    $itemExplode = explode(':',$item);
    if(empty($itemExplode[0]) || empty($itemExplode[1]))return $carry;
    $carry[$itemExplode[0]] = $itemExplode[1];
    return $carry;
},[]);

echo json_encode($styles); //{"padding":" 90px 0px 20px 0px"," background":" #000000"," display":" block"}
    
02.06.2017 / 16:57