douqian1296 2019-01-03 05:50
浏览 38

如何在PHP中推送重复条目?

Following is an object:

$obj = (object) [];
$obj->{'key1'} = 'val1';

Now, how do I push a key with same name but different value?

$obj = (object) [];
$obj->{'key1'} = 'val1';
$obj->{'key1'} = 'val2';

It just edits the key1. I know this is an expected behavior but do we have other workarounds?

I want the schema to be like:

"collection": {
    "obj1": "val1",
    "obj1": "val2"
}
  • 写回答

2条回答 默认 最新

  • dro59505 2019-01-03 05:58
    关注

    You can map the values in an array with "key1" as key:

    $obj = (object) [];
    $obj->key1 = ['val1', 'val2'];
    

    Output:

    {#183 ▼
      +"key1": array:2 [▼
        0 => "val1"
        1 => "val2"
      ]
    }
    

    Now, you can easily traverse for "key1" and get all the values.

    Thanks!

    评论

报告相同问题?