简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM