在PHP中将字符串拆分为数组

时间:2022-04-29 15:41:13

I want split a string which consists of products. Each product is encloded within {..}, and separated by comma.

我想拆分一个由产品组成的字符串。每个产品都被{..}包围,并以逗号分隔。

For instance, I have a strin below.

例如,我有一个strin下面。

[
{\"productid\" : \"prod:kj42j3d24-47c2-234lkj2-e3c2-cfc9a4a3b005\",\"memo\" : \"
product description
\",\"taxable\" : 0,\"unitweight\" : 0,\"unitcost\" : 0,\"unitprice\" : 12.34,\"quantity\" : 1.00},
{\"productid\" : \"prod:k324jl-462d-e589-aecf-32k4j\",\"memo\" : \"
prodict description
\",\"taxable\" : 0,\"unitweight\" : 0,\"unitcost\" : 0,\"unitprice\" : 12.23,\"quantity\" : 1}
]

and want to separate each product into different indexes of an array. Thanks.

并希望将每个产品分成不同的数组索引。谢谢。

3 个解决方案

#1


2  

Looks like JSON to me:

看起来像JSON给我:

$a = json_decode(" [ 
  {\"productid\" : \"prod:kj42j3d24-47c2-234lkj2-e3c2-cfc9a4a3b005\",
   \"memo\" : \" product description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.34,\"quantity\" : 1.00}, 
  {\"productid\" : \"prod:k324jl-462d-e589-aecf-32k4j\",
   \"memo\" : \" prodict description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.23,\"quantity\" : 1} ] ", true
);

#2


1  

your string looks a lot like a JSON-encoded array of objects. Try using the php function json_decode.

你的字符串看起来很像JSON编码的对象数组。尝试使用php函数json_decode。

$parsed_array = json_decode($str);

#3


1  

In this particular case, it appears like your string is already in JSON format. PHP has inbuilt support for this. To take this string and make it a JSON object, use the json_decode function.

在这种特殊情况下,您的字符串似乎已经是JSON格式。 PHP内置了对此的支持。要获取此字符串并使其成为JSON对象,请使用json_decode函数。

More information in the PHP manual here: http://www.php.net/manual/en/function.json-decode.php

有关PHP手册的更多信息,请访问:http://www.php.net/manual/en/function.json-decode.php

#1


2  

Looks like JSON to me:

看起来像JSON给我:

$a = json_decode(" [ 
  {\"productid\" : \"prod:kj42j3d24-47c2-234lkj2-e3c2-cfc9a4a3b005\",
   \"memo\" : \" product description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.34,\"quantity\" : 1.00}, 
  {\"productid\" : \"prod:k324jl-462d-e589-aecf-32k4j\",
   \"memo\" : \" prodict description \",\"taxable\" : 0,\"unitweight\" : 0,
   \"unitcost\" : 0,\"unitprice\" : 12.23,\"quantity\" : 1} ] ", true
);

#2


1  

your string looks a lot like a JSON-encoded array of objects. Try using the php function json_decode.

你的字符串看起来很像JSON编码的对象数组。尝试使用php函数json_decode。

$parsed_array = json_decode($str);

#3


1  

In this particular case, it appears like your string is already in JSON format. PHP has inbuilt support for this. To take this string and make it a JSON object, use the json_decode function.

在这种特殊情况下,您的字符串似乎已经是JSON格式。 PHP内置了对此的支持。要获取此字符串并使其成为JSON对象,请使用json_decode函数。

More information in the PHP manual here: http://www.php.net/manual/en/function.json-decode.php

有关PHP手册的更多信息,请访问:http://www.php.net/manual/en/function.json-decode.php