I have following JSON object
[{ "item":"foo", "category_id":1 },{ "item":"bar", "category_id": 2},{ "item":"bar", "category_id":3}]
needs to convert as follows:
[{ "item":"foo", "category_id":1 },{ "item":"bar", "related": { "category_id": [2, 3] }}]
I am writing a php function as
$previous = [];
$category = [];
$result = [];
foreach ($jsonData as $element) {
if (in_array($element['item'], $previous)) {
$category[] = $element['category_id'];
$result[] = $category;
} else {
$previous[] = $element['item'];
$result[] = $element;
}
}
echo json_encode($result);
which gives output as
[{"item":"foo","category_id":1},{"item":"bar","category_id":2},[3]]
but i am not able to get the JSON as sub object. How can i solve it?