在php中对象顶部的stdClass中添加属性 [英] Add property to stdClass at the top of the object in php

查看:105
本文介绍了在php中对象顶部的stdClass中添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

php 中创建用于返回JSON的对象时,是否可以添加属性并强制其位于顶部?我很喜欢这样做,因为该对象是通过API公开的,并且顶部最好有ID.

When creating a object in php used to return JSON is it possible to add a property and force it to go at the top? I'd like this since the object is exposed via an API and it is nice to have ids at the top.

例如:

$obj = new stdClass();
$obj->name = 'John';
$obj->age = 26;
$obj->id = 3645;

当您json_encode()时,它变成:

{
    "name": "John",
    "age": 26,
    "id": 3645
}

是否有一种方法可以强制id在对象的顶部,即使最后添加它也是如此?注意,由于其他相关代码,我不能简单地在添加nameage之前先添加id.

Is there a way to force id at the top of the object even though it is added last? Note, I can't simply just add id before adding name and age because of other dependent code.

推荐答案

如果使用关联数组而不是对象(即

It's easily possible if you use an associative array instead of an object, i.e.

$x = ['name' => 'john', 'age' => 26]; // or: $x = (array)$obj
$x = ['id' => 123] + $x;
echo json_encode($x);
// {"id":123,"name":"john","age":26}

但是,请务必注意,在JSON中,未定义属性排序,并且不应依赖.如果您当前拥有的东西行得通,那么这种更改实际上将毫无用处.

However, it's important to note that in JSON property ordering is not defined and should not be relied upon. If what you currently have works, this change would be rather useless in fact.

这篇关于在php中对象顶部的stdClass中添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆