1

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

           )

)
5
  • 9
    $array[] = $object; ? Commented Jan 18, 2016 at 11:32
  • 1
    do as you simply do for adding values into array. Commented Jan 18, 2016 at 11:33
  • 1
    @AlexAndrei is correct. This is the simplest way to do so. Commented Jan 18, 2016 at 11:34
  • Then you don't have an object yet. Commented Jan 18, 2016 at 11:35
  • @monir009 What do you mean? Commented Jan 18, 2016 at 11:44

4 Answers 4

3

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');

Sign up to request clarification or add additional context in comments.

Comments

2

Here is the solution you can try it

$object = new ClassName();
$object->name = "Some_value";
$myArray[] = $object;

Comments

1

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);

Comments

1

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);

?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.