Good afternoon everyone,
Is any simple way to unserialize that type of data and put everyone into Array()
$variable= "'Body Style'=>'SEDAN 4 DOOR';'CD Player'=>'PRESENT';'Color'=>'GRAY';'Engine Size'=>'3.0L V6 FI F';'Air Bags'=>'4';'Radio'=>'PRESENT';'Tape Deck'=>'N/A';'Estimated Repair Cost'=>'5518';'ACV'=>'6122';'Driver Airbag'=>'INTACT';'Passenger Airbag'=>'INTACT';'Left Side Airbag'=>'INTACT';'Right Side Airbag'=>'INTACT';'VIN Status'=>'OK';'Interior Color'=>'GRAY';'Airbag'=>'INTACT';'KeyFob'=>'PRESENT';";
without using explode()
, foreach()
and then preg_match
functions?
Thank you for answer.
Is any simple way to unserialize that type of data and put everyone into Array() without using using explode(), foreach() and then preg_match functions?
Yes, you can use preg_match_all()
.
if (preg_match_all("/'(.*?)'=>'(.*?)';/", $variable, $matches)) {
$result = array_combine($matches[1], $matches[2]);
print_r($result);
}
Output:
Array
(
[Body Style] => SEDAN 4 DOOR
[CD Player] => PRESENT
[Color] => GRAY
[Engine Size] => 3.0L V6 FI F
[Air Bags] => 4
[Radio] => PRESENT
[Tape Deck] => N/A
[Estimated Repair Cost] => 5518
[ACV] => 6122
[Driver Airbag] => INTACT
[Passenger Airbag] => INTACT
[Left Side Airbag] => INTACT
[Right Side Airbag] => INTACT
[VIN Status] => OK
[Interior Color] => GRAY
[Airbag] => INTACT
[KeyFob] => PRESENT
)
The advantage of this approach is it works even if any key or value contains semicolons such as Body;Style
or SEDAN;4 DOOR
which would make the explode()
approach fail.
You can use eval
to assign the contents of $variable
to another variable as an array, like this:
$variable= "'Body Style'=>'SEDAN 4 DOOR';'CD Player'=>'PRESENT';'Color'=>'GRAY';'Engine Size'=>'3.0L V6 FI F';'Air Bags'=>'4';'Radio'=>'PRESENT';'Tape Deck'=>'N/A';'Estimated Repair Cost'=>'5518';'ACV'=>'6122';'Driver Airbag'=>'INTACT';'Passenger Airbag'=>'INTACT';'Left Side Airbag'=>'INTACT';'Right Side Airbag'=>'INTACT';'VIN Status'=>'OK';'Interior Color'=>'GRAY';'Airbag'=>'INTACT';'KeyFob'=>'PRESENT';";
$variable = str_replace(';', ',', $variable);
eval("\$array = [$variable];");
print_r($array);
The use of eval
, however, is greatly discouraged. See here: http://php.net/manual/en/function.eval.php
I'm assuming you're getting the contents of $variable
from somewhere else. Is there any particular reason you have the data in that format and not in json, for example?
EDIT: I just realized the code won't work as is, because the values of the array are separated by semicolons and not by colons. You need to replace the semicolons with colons first. I've updated the code to reflect that.