简体   繁体   中英

Correctly Format JSON Output in PHP

I am retrieving the name of an employee from one API and need to format some JSON to transmit it over an outgoing api. I need my output to look like this.

A {"employees":[{"name":"Charles Johnson"}]}

Right now my output looks like this:

B {"employees":"[{\"name\":\"Robert Johnson\"}]"}

based on the following code:

$employee = "Robert Johnson";//string retrieved from API
$return = json_encode(array(array('name'=>$employee)));

echo json_encode(array('employees'=>$return));

How can I convert B so it looks like A. Note I would prefer not to alter the last line (echo...) as it is used for various other things as well. 'd like to prep $return so that it echoes out in the form of A.

Thanks for any suggestions.

Json encode is required only once after preparing all the data. Please find the below code hope it will help you.

$employee = "Robert Johnson";//string retrieved from API
$return =array(array('name'=>$employee));

echo json_encode(array('employees'=>$return));

You encode JSON data twice so just do it once, in last line that outputs it.

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