如何将元素动态添加到SplObjectStorage对象的数组值

时间:2018-02-28 08:27:32

标签: php oop

假设我们有一个索引

class Index{
    /* indexing fields */
    public $id ;
    public $word;

    /* Constructor */
    public function __construct($id, $word)
    {
        $this->id = $id;
        $this->word = $word;
    }

}

到目前为止一切顺利?确定。

现在,想象一下我们必须实现一个将单词映射到他们的同义词的字典。

/* Create SplObjectStorage object. should work as data-structure that 
     resembles a HashMap or Dictionary */
     $synonymsDictionary = new \SplObjectStorage(); 

/* Create a word index object, and add it to synonyms dictionary */
    $word = new Index(1,"bad");
    $synonymsDictionary[$word] = array("evil", "mean", "php");

/* print it out */
    echo var_dump($synonymsDictionary[$word]);

输出:

array(3) {
 [0]=>
   string(4) "evil"
 [1]=>
   string(4) "mean"
 [2]=>
   string(3) "php"
 }

如果想要在我们的单词中添加一个同义词,那该怎么办呢?我试过这个:

/* Adding one more synonym */
   $synonymsDictionary->offsetGet($word)[] = "unlucky"; 
   echo var_dump($synonymsDictionary[$word]);

然而,输出与上面相同的输出:

     array(3) {
        [0]=>
   string(4) "evil"
        [1]=>
   string(4) "mean"
        [2]=>
   string(3) "php"
 }

我错过了什么?

1 个答案:

答案 0 :(得分:0)

将所有同义词保存为数组而不是单个字符串:

php bin/console doctrine:mapping:import --force App annotation

现在您可以添加新项目$synonymsDictionary[$word] = array("evil", "mean", "php");

此外$synonymsDictionary[$word][] = 'unlucky'仅返回数据,而不是数据引用。因此,您以后更改的内容永远不会被分配回同义词词典。

所以你需要这个:

offsetGet
相关问题