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

Asked

Viewed 88 times

0

I have a register in the json database and inside it there is a "style" object in which it has an inline css code, for example:

"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 take each parameter and transform it into an array where it would look like this, generating an array or Json (I don’t know which is the best solution), follows an example of what I want:

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

Because I will take this result and water an input for each key, generating a form so that the user can change the values.

The closest I could get was 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 generating an array and inside it other arrays, I would like to leave all returns inside an array just as for example this is the return:

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

Is that the way? Or better to follow another totally different way?

1 answer

1

You can use array_reduce to generate it at once, follows 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"}
  • Gee Antonio, thank you very much.... picking up the result via ajax I can do exactly what I need to do. I confess that I have been for a while breaking my head with this, today I thank you for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.