0

Tried searching but nothing was exactly what I was looking for.

I have a string that looks like this:

$string = "sku1,2|sku2,5";

I would like to convert it into a multi-dimensional array that would end up looking like this:

Array
(
    [0] => Array
        (
            [sku] => sku1
            [qty] => 2
        )

    [1] => Array
        (
            [sku] => sku2
            [qty] => 5
        )

)

So far I've tried using:

explode(',',$string);

Which is the right idea but it doesn't account for the pipe delimiter to know when to go to the next array group.

dmotors
  • 611
  • 2
  • 7
  • 19
  • Are the keys just given or do they come from anywhere? (`sku`, `qty`) – Rizier123 Jul 24 '15 at 21:18
  • If you mean the [sku] and [qty] I purposely named it. So your example before you deleted it was right on point just needed an extra to name those keys and should be perfect. However, even if I don't I can access it by [0] and [1]. I just named it to make it more readable friendly. – dmotors Jul 24 '15 at 21:21

3 Answers3

1

You are on the right way, but you have to start with the pipe. So first explode() your sting by the pipe, then go through each element with array_map() and explode it by the comma.

To get the associative keys, just array_combine() your exploded array with the keys, which you want, e.g.

$array = array_map(function($v){
    return array_combine(["sku", "qty"], explode(",", $v));
}, explode("|", $string));

print_r($array);
Rizier123
  • 58,877
  • 16
  • 101
  • 156
1

I wouldn't even bother with looking for | or manually traversing anything. You can generate the desired array already with preg_match_all containing just a few fillers:

preg_match_all(
    "/(?<sku>\w+),(?<qty>\d+)\K/",
    $string, $array, PREG_SET_ORDER
);

This simply extracts any combination of alphanumeric \w+ and numeric \d+ entries delimited by , comma.

mario
  • 144,265
  • 20
  • 237
  • 291
  • The output seems to show more than it's supposed to: [0] => [sku] => sku1 [1] => sku1 [qty] => 2 [2] => 2 – dmotors Jul 24 '15 at 21:31
  • @dmotors: Yes, it doubles the keys numerically ("a few fillers"). A regex-approach mostly makes sense to constrain/assert the input further. For other/simpler approaches (such as `parse_str`) see [PHP Split Delimited String into Key/Value Pairs (Associative Array)](http://stackoverflow.com/q/5290342) – mario Jul 24 '15 at 21:34
  • Understood. That is not a problem I guess I overlooked what you meant by "a few fillers". – dmotors Jul 24 '15 at 21:37
0

Not the most elegant solution but this should work for you:

$string = "sku1,2|sku2,5";

$explodePipe = explode('|', $string);

$resultArray = array();

foreach ($explodePipe as $explodedPipe) {
    $explodeSku = explode(',', $explodedPipe);
    $resultArray[]['sku'] = $explodeSku[0];
    $resultArray[]['qty'] = $explodeSku[1];
}