Home > Backend Development > PHP Problem > How to convert json object to string array object in php

How to convert json object to string array object in php

PHPz
Release: 2023-04-18 10:00:02
Original
477 people have browsed it

In PHP, the json_decode function can parse a JSON string into an object or array in PHP, while the json_encode function can convert a PHP object or array into a JSON string. But sometimes we need to convert JSON objects into string array objects, what should we do?

Suppose our JSON string looks like this:

{
    "name": "Tom",
    "age": 18,
    "hobbies": ["reading", "running", "swimming"]
}
Copy after login

We can use the following PHP code to convert it into a string array object:

$json = '{"name":"Tom","age":18,"hobbies":["reading","running","swimming"]}';
$data = json_decode($json, true);

$keys = array_keys($data);
$values = array_values($data);

$str_arr = [];
for ($i = 0; $i < count($keys); $i++) {
    if (is_array($values[$i])) {
        $str_arr[$keys[$i]] = json_encode($values[$i]);
    } else {
        $str_arr[$keys[$i]] = (string) $values[$i];
    }
}

var_dump($str_arr);
Copy after login

First, we will Pass the JSON string to the json_decode function and set the second parameter to true, which means converting the parsed JSON into an associative array.

Next, we use the array_keys function to get the key name of the associative array, and use the array_values ​​function to get the value of the associative array.

Then, we traverse all key names and values ​​through a for loop and determine whether the value is an array. If the value is an array, we will use the json_encode function to convert it to a JSON string; if it is not an array, we will use a cast to convert it to a string.

Finally, we use the key name as the key and the string as the value to build a new associative array. Using the var_dump function to output the results, you can get the following output:

array(3) {
  ["name"]=>
  string(3) "Tom"
  ["age"]=>
  string(2) "18"
  ["hobbies"]=>
  string(28) "["reading","running","swimming"]"
}
Copy after login

As you can see, we successfully converted the JSON object into a string array object. Among them, the key step is to use the json_encode function to convert the array into a JSON string.

The above is the detailed content of How to convert json object to string array object in php. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template