0

How do I split the following string which is seperated by the ',' delimiter to an array in PHP?

String:

[{"sku":"PAP","name":"Butter","price":23,"quantity":2},{"sku":"PER","name":"Garlic","price":25,"quantity":1}]

Required Array:

$array[0]= "sku":"PAP","name":"Butter","price":23,"quantity":2

$array[1]= "sku":"PER","name":"Garlic","price":25,"quantity":1

I am not able to split based on the delimiter',' since it is present in the array elements.

2
  • 2
    The string looks very much like JSON. So you should use json_decode function: $array = json_decode($json, true); Commented Dec 17, 2016 at 7:27
  • You should be using a JSON parser here, not a regex. Even more true if the JSON is nested. Commented Dec 17, 2016 at 7:28

3 Answers 3

1

@Ruslan Osmanov is right. Just decode like JSON.

<?php
  $a='[{"sku":"PAP","name":"Butter","price":23,"quantity":2},{"sku":"PER","name":"Garlic","price":25,"quantity":1}]';
  print_r(json_decode($a));
?>

Result:

Array
(
    [0] => stdClass Object
        (
            [sku] => PAP
            [name] => Butter
            [price] => 23
            [quantity] => 2
        )

    [1] => stdClass Object
        (
            [sku] => PER
            [name] => Garlic
            [price] => 25
            [quantity] => 1
        )

)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that helps .Could you also suggest me how to assign each element to an array.. I am not able to access the individual elements of the decoded json string
1

First, remove the unwanted characters:

$str=str_replace("[{","",$str);
$str=str_replace("}]","",$str);

Then, split with:

$array=preg_split("},{",$str);

Comments

0

string looks like in JSON so please use json_decode() method of php.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.