Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/226.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将JSON对象转换为子对象_Php_Json - Fatal编程技术网

Php 将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

我有以下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 = [];
$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”:}
(字段名,但没有值)。它现在用正确的值更新。