How do I split the following string which is seperated by the ',' delimiter to an array in PHP?
如何将以下由','分隔符分隔的字符串拆分为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.
我无法根据分隔符','进行拆分,因为它存在于数组元素中。
3 个解决方案
#1
0
@Ruslan Osmanov is right. Just decode like JSON.
@Ruslan Osmanov是对的。就像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
)
)
#2
0
First, remove the unwanted characters:
首先,删除不需要的字符:
$str=str_replace("[{","",$str);
$str=str_replace("}]","",$str);
Then, split with:
然后,拆分:
$array=preg_split("},{",$str);
#3
0
string looks like in JSON so please use json_decode() method of php.
字符串看起来像JSON所以请使用php的json_decode()方法。
#1
0
@Ruslan Osmanov is right. Just decode like JSON.
@Ruslan Osmanov是对的。就像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
)
)
#2
0
First, remove the unwanted characters:
首先,删除不需要的字符:
$str=str_replace("[{","",$str);
$str=str_replace("}]","",$str);
Then, split with:
然后,拆分:
$array=preg_split("},{",$str);
#3
0
string looks like in JSON so please use json_decode() method of php.
字符串看起来像JSON所以请使用php的json_decode()方法。