【问题标题】:Merge a Php array into a Php object将一个 Php 数组合并到一个 Php 对象中
【发布时间】:2017-01-03 16:48:20
【问题描述】:

我需要将一个 php 数组合并到一个 php 对象中。

我需要我的 php 对象看起来像这样:

{"info1":"value","concurrents":[{"concurrent1":"value"},{"concurent2":"value"}],"info3":"value"};

,我实际上得到了这样的初始对象:

$initial = pg_fetch_object($result);

之后,我用这个命令获取数组:

$concurrents = pg_fetch_all($result);

请问,我如何将 $concurrents 合并到我的 $initial 对象中,以便最终将其执行到前端:

print_r(json_encode($initial));

我尝试了foreach,但它不起作用。

【问题讨论】:

  • 这很好,但是你在取什么?你试过什么?
  • 显示$initial$concurrents
  • 我正在使用 postgre 获取 sql 数据...我想将我的 JSON 对象返回给 angularJs,它工作得很好,除了我需要在我的 JSON OBJECT 中包含这个数组,它的常规 json 它可以工作除了我不知道如何用 php 后端生成它

标签: php json type-conversion


【解决方案1】:

您是否尝试过以下方法?

$initial->concurrents = $concurrents;

甚至:

$initial->concurrents = pg_fetch_all($result);

【讨论】:

    【解决方案2】:

    不要把你的初始结果作为一个对象,把它作为一个数组来获取:

    $initial = pg_fetch_assoc($result);
    

    然后“合并”相当容易(将初始值推到 concurrents 数组的开头):

    $concurrents = pg_fetch_all($result);
    array_unshift($concurrents, $initial);
    

    现在您可以打印它们了:

    print_r(json_encode($concurrents));
    

    【讨论】:

    • 非常感谢但是它会打印一个数组吗?因为前端angularjs需要一个Object,而不是数组,在这种特殊情况下,非常感谢你的回答。
    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多