Php 将JSON对象转换为子对象
我有以下JSON对象Php 将JSON对象转换为子对象,php,json,Php,Json,我有以下JSON对象 [{ "item":"foo", "category_id":1 },{ "item":"bar", "category_id": 2},{ "item":"bar", "category_id":3}] 需要按如下方式转换: [{ "item":"foo", "category_id":1 },{ "item":"bar", "related": { "category_id": [2, 3] }}] 我正在编写一个php函数 $previous = []; $cat
[{ "item":"foo", "category_id":1 },{ "item":"bar", "category_id": 2},{ "item":"bar", "category_id":3}]
需要按如下方式转换:
[{ "item":"foo", "category_id":1 },{ "item":"bar", "related": { "category_id": [2, 3] }}]
我正在编写一个php函数
$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);
输出为
[{"item":"foo","category_id":1},{"item":"bar","category_id":2},[3]]
但我无法将JSON作为子对象。
如何解决此问题?如果对象中数组的第一项是父节点,则可以访问第一项,将其复制到新对象,然后迭代下一项提取id,然后将其添加到“category_id”:数组您的第一个JSON对象不正确。您有一个
“category\u id”:}
(字段名,但没有值)。它现在用正确的值更新。