Home > Mobile >  Add array of objects with the dot notation
Add array of objects with the dot notation

Time:01-18

With the following code Arr::set($array, 'messages.to.email', $value);

That will generate an output like:

{
  "messages": {
    "subject": "this is out email",
    "to": {
       "email": "[email protected]"
    }
  }
}

My issue is that I need this output instead:

{
  "messages": [{
    "subject": "this is out email",
    "to": {
       "email": "[email protected]"
    }
  }]
}

Being messages an array of objects. I haven't been able to find a native way of doing it, so I'm thinking of manually adding something like messages[].to.email

Am I missing something? A magic helper or syntax? to achieve what I'm looking for?

CodePudding user response:

If you used an index for the messages it would force it to be an array:

Arr::set($array, 'messages.0.to.email', $value);

This is just adding another level/container to this by specificying that there is something between 'messages' and 'to'. Could be named anything, but 0 is for zero indexed array here, which would be an array in JSON not an object.

  •  Tags:  
  • Related