Reputation: 165
Hello everyone I have an array of objects like below. I just want to add new object into current array. Any help how to do it. Thanks
Array
(
[0] => stdClass Object
(
[sm_id] => 1
[c_id] => 1
)
[1] => stdClass Object
(
[sm_id] => 1
[c_id] => 2
)
)
Output should be
Array
(
[0] => stdClass Object
(
[sm_id] => 1
[c_id] => 1
)
[1] => stdClass Object
(
[sm_id] => 1
[c_id] => 2
)
[2] => stdClass Object
(
[sm_id] => 1
[c_id] => 3
)
)
Upvotes: 1
Views: 160
Reputation: 338
Here is the solution you can try it
$object = new ClassName();
$object->name = "Some_value";
$myArray[] = $object;
Upvotes: 2
Reputation: 164
try it:
<?php
//your default array
$your_array = array(0=> (object) array("sm_id"=>1, "c_id"=>1), 1=>(object) array("sm_id"=>1, "c_id"=>2));
//add object in your array
array_push($your_array, (object) array("sm_id"=>1, "c_id"=>3));
//show list
print_r($your_array);
?>
Upvotes: 1
Reputation: 3195
You can do it using array_merge()
$array = array((object)array('sm_id' => 1,'c_id' => 1),(object)array('sm_id' => 1,'c_id' => 2));//Your object array;
$myarry[] = array('sm_id' => 1,'c_id' => 3); // Additional Array
$finalarr = (object) array_merge((array)$array, (array)$myarry);
Upvotes: 1
Reputation: 118
Try this,
$object = new stdClass();
$object->sm_id = "1";
$object->c_id = "3";
$myArray[] = $object;
(or)
$myArray[] = (object) array('sm_id' => '1','c_id'=>'3');
Upvotes: 3