duanguochi6194 2016-11-18 12:58
浏览 10
已采纳

转换填充了对象的数组

I have an array that give objects back like this:

array (size=61)
  0 => 
    object(Xxx\Car)[602]
      private 'id' => int 53
      private 'name' => string 'Volkswagen' (length=10)
  1 => 
    object(Xxx\Car)[594]
      private 'id' => int 43
      private 'name' => string 'Toyota' (length=6)
  2 => 
    object(Xxx\Car)[595]
      private 'id' => int 32
      private 'name' => string 'BMW' (length=3)

How can I convert the array to so that the id become the key and the value the description, like this:

array (size=61)
  53 => 'Volkswagen'
  43 => 'Toyota'
  32 => 'BMW'

I've tried

$cars = array();    
foreach ($result as $key => $value) {
    $cars[$value['id']] = $value['name'];
}

But that doesn't work.

  • 写回答

2条回答 默认 最新

  • douhe4336 2016-11-18 13:01
    关注

    You are treating your objects as if they were arrays.

    $array['key'] is the notation for accessing an element in an array, but $object->key is the one for an object.

    Try this :

    $cars = array();    
    foreach ($result as $key => $value) {
        $cars[$value->id] = $value->name;
    }
    

    EDIT : If that doesn't work (due to the private nature of the elements), you might have to declare functions like getID() and getName() in your object class file, and use them as such :

    $cars = array();    
    foreach ($result as $key => $value) {
        $cars[$value->getID()] = $value->getName();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成
  • ¥15 HC32L176调试了一个通过TIMER5+DMA驱动WS2812B
  • ¥15 cocos的js代码调用wx.createUseInfoButton问题!
  • ¥15 关于自相关函数法和周期图法实现对随机信号的功率谱估计的matlab程序运行的问题,请各位专家解答!
  • ¥15 Python程序,深度学习,有偿私