In PHP, how can I add an object element to an array?

后端 未结 4 799
心在旅途
心在旅途 2020-12-05 09:25

I\'m using PHP. I have an array of objects, and would like to add an object to the end of it.

$myArray[] = null; //adds an element
$myArray[count($myArray) -         


        
相关标签:
4条回答
  • 2020-12-05 09:58

    Here is a clean method I've discovered:

    $myArray = [];
    
    array_push($myArray, (object)[
            'key1' => 'someValue',
            'key2' => 'someValue2',
            'key3' => 'someValue3',
    ]);
    
    return $myArray;
    
    0 讨论(0)
  • 2020-12-05 10:03

    Just do:

    $object = new stdClass();
    $object->name = "My name";
    $myArray[] = $object;
    

    You need to create the object first (the new line) and then push it onto the end of the array (the [] line).

    You can also do this:

    $myArray[] = (object) ['name' => 'My name'];
    

    However I would argue that's not as readable, even if it is more succinct.

    0 讨论(0)
  • 2020-12-05 10:08

    Something like:

    class TestClass {
    private $var1;
    private $var2;
    
    private function TestClass($var1, $var2){
        $this->var1 = $var1;
        $this->var2 = $var2;
    }
    
    public static function create($var1, $var2){
        if (is_numeric($var1)){
            return new TestClass($var1, $var2);
        }
        else return NULL;
    }
    }
    
    $myArray = array();
    $myArray[] = TestClass::create(15, "asdf");
    $myArray[] = TestClass::create(20, "asdfa");
    $myArray[] = TestClass::create("a", "abcd");
    
    print_r($myArray);
    
    $myArray = array_filter($myArray, function($e){ return !is_null($e);});
    
    print_r($myArray);
    

    I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.

    Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.

    0 讨论(0)
  • 2020-12-05 10:09

    Do you really need an object? What about:

    $myArray[] = array("name" => "my name");
    

    Just use a two-dimensional array.

    Output (var_dump):

    array(1) {
      [0]=>
      array(1) {
        ["name"]=>
        string(7) "my name"
      }
    }
    

    You could access your last entry like this:

    echo $myArray[count($myArray) - 1]["name"];
    
    0 讨论(0)
提交回复
热议问题