Reputation:
I want to convert my string into array, Im giving you examples of what i want and what Ive tried. My string looks like this:
Height:
3/16
Color:
Standard Red
Material:
Die-cut, pressure-sensitive paper
Package Quantity:
1000/Pkg
Reusable:
Yes
Size:
3/16 H x 1/4 W
I want it to convert it in array to look like this:
Array
(
[0] => Height: 3/16
[1] => Color: Standard Red
[2] => Material: Die-cut, pressure-sensitive paper
[3] => Package Quantity: 1000/Pkg
[4] => Reusable: Yes
[5] => Size: 3/16 H x 1/4 W
)
I tried with this:
$array = explode("\n", $string);
But Ive got this for the result:
Array
(
[0] => Height:
[1] => 3/16
[2] => Color:
[3] => Standard Red
[4] => Material:
[5] => Die-cut, pressure-sensitive paper
[6] => Package Quantity:
[7] => 1000/Pkg
[8] => Reusable:
[9] => Yes
[10] => Size:
[11] => 3/16 H x 1/4 W
[12] =>
)
Upvotes: 1
Views: 112
Reputation: 785
You can use something like this:
preg_match_all('/(?<key>.+):\n(?<value>.+)/', $s, $a);
$result = array_combine($a['key'], $a['value']);
print_r($result);
output:
Array
(
[Height] => 3/16
[Color] => Standard Red
[Material] => Die-cut, pressure-sensitive paper
[Package Quantity] => 1000/Pkg
[Reusable] => Yes
[Size] => 3/16 H x 1/4 W
)
So, you need only these 2 functions to use: array_combine() preg_match_all()
Upvotes: 0
Reputation: 17417
You're on the right track by separating the string into lines. You then need to group the array into pairs of lines, and implode
them together. Here I'm using array_map
to modify each of the pairs at once, but you could also do this for a simple for-loop if it's clearer.
$lines = explode("\n", trim($string));
$combined = array_map(
function($line) { return implode(' ', $line); },
array_chunk($lines, 2)
);
$combined
should now match the output in your question. See https://3v4l.org/ZdgWS for a full example.
Upvotes: 1