dsn5510 2018-06-28 08:12
浏览 70

如何使用foreach php创建具有相同属性的多个对象

I have search for creating multiple objects with same properties but didn't find a solution. So I am creating this object.

$monthData = new \stdClass();
foreach($quotesData as $datas){

   $monthData->name =  $datas[0] ["monthname"];
   $monthData->data = $datas[0] ["price"];
}

but it is only creating one object

and when i am doing $monthData[$i]->name then php throws an exception Cannot use object of type stdClass as array in file

so I want the resultant object like this

{
        name: 'Jane',
        data: [1, 0, 4]
    }, {
        name: 'John',
        data: [5, 7, 3]
    }

but it gave me only one object in return at this time

   {
        name: 'Jane',
        data: [1, 0, 4]
    }
  • 写回答

2条回答 默认 最新

  • douw92892 2018-06-28 08:17
    关注

    I have search for creating multiple objects with same properties but didn't find a solution

    No. It works as you wrote it - read your code again. What you do is: you create new object and then you loop and change that object's properties. If you need multiple objects then you need to create the in your loop:

    foreach(...) {
       $obj = new ...
       $obj-> ...
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号