是否可以编辑json数组的元素以容纳其他数据/元素?

时间:2020-08-09 11:34:10

标签: php json

我正在从数据库中检索数据并将其推入数组,然后使用json_encode()以json格式输出。我最终已经有了这种格式的数据。

[
    {
        "category_id": "1",
        "category_name": "Construction Materials"
    },
    {
        "items": [
            {
                "id": "1",
                "item_name": "Wire Mesh",
                "price": "459",
                "image_url": null
            },
            {
                "id": "2",
                "item_name": "Cement",
                "price": "700",
                "image_url": null
            },
            {
                "id": "3",
                "item_name": "Barbed Wire",
                "price": "3000",
                "image_url": null
            },
            {
                "id": "4",
                "item_name": "Iron sheet",
                "price": "200",
                "image_url": null
            }
        ]
    },
    {
        "category_id": "2",
        "category_name": "Plumbing"
    },

这是我要实现的目标:

[
    {
        "category_id": "1",
        "category_name": "Construction Materials"
        "items": [
            {
                "id": "1",
                "item_name": "Wire Mesh",
                "price": "459",
                "image_url": null
            },
            {
                "id": "2",
                "item_name": "Cement",
                "price": "40",
                "image_url": null
            },
            {
                "id": "3",
                "item_name": "Barbed Wire",
                "price": "3000",
                "image_url": null
            },
            {
                "id": "4",
                "item_name": "Iron sheet",
                "price": "200",
                "image_url": null
            }
        ]
    },
    {
        "category_id": "2",
        "category_name": "Plumbing"
    },

如何在php中实现这一目标。是否可以编辑主数组的内容?如何在“ category_name”之后添加“ items” 问候。

2 个答案:

答案 0 :(得分:0)

function get_first_property($object) {
    $properties = array_keys(get_object_vars($object));
    return reset($properties);
}
function object_merge($object1, $object2) {
    return (object) array_merge((array) $object1, (array) $object2);
}

// loop through each of the array objects
$previous_first_property = null;
foreach ($array as $i => $object) {
    $first_property = get_first_property($object);
    
    // merge if the 1st property is "items", and the previous 1st was "category_id"
    if ($first_property == "items" && $previous_first_property == "category_id") {
        $array[$i - 1] = object_merge($array[$i - 1], $array[$i]);
        unset($array[$i]);
    }
    
    $previous_first_property = $first_property;
}

答案 1 :(得分:0)

$array = json_decode($yourJson);
$arrayLength = count($array);
$finalArray = [];
for ($i=0; $i < $arrayLength; $i+=2) {
    $finalArray[] = $array[$i] + $array[$i + 1];
}
$backToJson = json_encode($finalArray);

替代Mattijs的答案。