This question already has an answer here:
- Create JSON object using PHP 5 answers
I'm trying to create JSON in a PHP variable that represents the following JSON structure:
{
"nodes": [
{"id": "example@email.com", "group": 1},
{"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2},
{"id": "Device ID 9057673495b451897d14f4b55836d35e", "group": 2}
],
"links": [
{"source": "example@email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1},
{"source": "example@email.com", "target": "Exact ID 9057673495b451897d14f4b55836d35e", "value": 1}
]
}
I'm currently not certain if the best way to do this would be to manually format the JSON layout myself, or if the above structure can be achieved using arrays and json_encode(). It would be good it someone could first confirm the best approach here.
The code I currently have is:
$entityarray['nodes'] = array();
$entityarray['links'] = array();
$entityarray['nodes'][] = '"id": "example@email.com", "group": 1';
$entityarray['nodes'][] = '"id": "Device ID 0eb6823c8e826b6ba6a4fba7459bc77c", "group": 2';
$entityarray['links'][] = '"source": "example@email.com", "target": "Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c", "value": 1';
However when I view the output in JSON format there are some issues:
{
"nodes": ["\"id\": \"example@email.com\", \"group\": 1", "\"id\": \"Device ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"group\": 2"],
"links": ["\"source\": \"example@email.com\", \"target\": \"Exact ID 0eb6823c8e826b6ba6a4fba7459bc77c\", \"value\": 1"]
}
As you can see the json_encode is causing additional quotation marks with escape \ characters to be added, and each entry isn't stored as an object. Any guidance you can provide would be sincerely appreciated.
</div>