从Eloquent查询中更改对象数组中的键

I have an array of objects coming from an Eloquent query:

[
    {
        "id": 1,
        "user_id": 1,
        "name": null,
        "link": "storage/images/foo.png"       
    },
    {
        "id": 2,
        "user_id": 1,
        "name": null,
        "link": "storage/images/foo.png"
    },
    {..}
]

In PHP, what would be the most efficient way to rename the "link" key to "url" in every object in the array? Keeping the same order of elements would be a bonus.

I'm hopeful to achieve this:

[
    {
        "id": 1,
        "user_id": 1,
        "name": null,
        "url": "storage/images/foo.png"       
    },
    {
        "id": 2,
        "user_id": 1,
        "name": null,
        "url": "storage/images/foo.png"
    },
    {..}
]

As my comment seemed to be the correct way, and for sure faster than looping over an already generated array ill post it as an answer here.

guessing you are using eloquent to get ur data

User::all() 

or something alike, try making it a select query as follow:

User::select('id, user_id, link as url')->get(); 

to have this fixed for you

For future visitors.

This answer is based on OP's original request of how to rename object keys using PHP. Upon further clarification, OP mentioned that they have access to change the DB query.

However, this answer is a very viable way to alter keys if you do not have access to the source data such as pulling JSON from someone else's server.


It's quite simple. You need to loop, set, and unset:

// Loop the array and get each object into $v by reference
// Objects pass-by-reference by default since PHP 5.0 so no need for &$v in this situation
foreach( $arr as $v )
{
    // Since $v is an object reference, manipulate it directly by setting a url
    $v->url = $v->link;

    // We can unset link
    unset( $v->link );
}

Because link was last anyways, we are able to simply add url to the end and remove link.

If link was in the middle somewhere then this solution would have been a bit trickier because we would have needed to maintain two arrays.