开发者

Splitting string into an array in PHP

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.

[
{\"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.


Looks like JSON to me:

$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
);


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

$parsed_array = json_decode($str);


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.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜