首页 > 解决方案 > 将对象插入 JSON 对象

问题描述

我正在尝试将 json 对象添加到从我的数据库下载的对象中,但是当我添加对象时,它并没有真正位于对象中的同一位置,它会将每个附加对象添加为第一个对象的子对象。请看下文。

Array
(
    [0] => stdClass Object
        (
            [component] => fork
            [date_] => 06/08/2019
            [servicetype] => rtyrtyrty
        )

    [1] => Array
        (
            [0] => stdClass Object
                (
                    [component] => fork
                    [date_] => 20/05/2019
                    [servicetype] => rtyrtyrty
                )
        )

    [2] => Array
        (
            [0] => stdClass Object
                (
                    [component] => fork
                    [date_] => 10/02/2019
                    [servicetype] => rtyrtyrty
                )
        )

    [3] => Array
        (
            [0] => stdClass Object
                (
                    [component] => fork
                    [date_] => 11/12/2018
                    [servicetype] => rtyrtyrty
                )
        )
)

我一直在尝试使用 json_decode() 将原始对象转换为数组,然后使用 push 函数:array_push($array1, $array2); 我似乎无法避免得到上述结果。

  originalObj= json_decode($newObj);
  array_push($originalObj, $newObj);
  $encodeForServerUpload = json_encode($originalObj);

标签: php

解决方案


改用这个:

$originalObj= json_decode($newObj);
array_push($originalObj, $newObj[0]);
$encodeForServerUpload = json_encode($originalObj);

推荐阅读