doujiao9866
2018-07-31 11:36
浏览 54
已采纳

从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"
    },
    {..}
]

图片转代码服务由CSDN问答提供 功能建议

我有一个来自Eloquent查询的对象数组:

 <  code> [
 {
“id”:1,
“user_id”:1,
“name”:null,
“link”:“storage / images / foo.png”
},\  n {
“id”:2,
“”user_id“:1,
”name“:null,
”link“:”storage / images / foo.png“
},
 {..  } 
] 
   
 
 

在PHP中,在数组中的每个对象中将“link”键重命名为“url”的最有效方法是什么? 保持相同的元素顺序将是一个奖励。

我希望能够实现这一目标:

  [
 {
“id”:1,
“user_id”  :1,
“name”:null,
“url”:“storage / images / foo.png”
},
 {
“id”:2,
“user_id”:1,\  n“name”:null,
“url”:“storage / images / foo.png”
},
 {..} 
] 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongzhi6463 2018-07-31 11:57
    已采纳

    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

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doufuxing8691 2018-07-31 11:38

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题