如何使用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]
    }

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-> ...
}

It's because you declare your $monthData as a single object, this means that when you loop through your data, the last item in the array actually sets the object data. You want to create an array then add the objects to the array:

$monthData = array();

foreach ($data as $key => $value)
{
    # define obj per loop
    $myObj = new \stdClass();

    # set obj data with loop data
    $myObj->data = $value['some_key'];
    # etc. etc.

    $monthData[] = $myObj;    
}

var_dump($monthData); # will display array of objects to use