简体   繁体   中英

how can convert json object to array in php?

I have this JSON

[size: null, color: "white"]

Which send to the server via post method.

I try

$your_json_string = json_decode($your_json_string, TRUE)

and

$your_json_string = html_entity_decode($your_json_string);
$your_json_string = json_decode($your_json_string, true);
  • With print_r($your_json_string); I get: null .
  • With echo json_last_error(); I get: 4 .

Any ideas on how I can solve this?

1) that is a json array [] not an object {}. 2) it will want property names quoted.

$String = <<< LOL
{"size": null, "color": "white"}
LOL;

print_r(json_decode($String,TRUE));

then you get

Array
(
    [size] =>
    [color] => white
)

If you have a wrong json string and you don't know how it will convert json to array in php. Example Below:

$string = '{test ing,test ingredients,test ingredients3,test ingredients4,test ingredients5}';

Trim your json string and remove non required data.

    $string = ltrim($string, '{');
    $string = rtrim($string, '}');

Remove comma from string and get normal php array

    $newSting = explode(',', $string);

Now you can loop through your data

foreach ($newSting as $key => $value) {
        echo $value;
    }
  

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