mardi 13 novembre 2018

Set key array without loop with Spread Operator in php

I use the php programming language with the Laravel framework, I want to enter the same data without having to use loops, the code that I have now:

$userIds = Subscriber::pluck('user_id')->toArray();

    $data = [];

    foreach ($userIds as $userId) {
        $dataTemporary = [
            'lang' => 'id',
            'is_read' => false,
            'is_count' => false,
            'user_id' => $userId,
        ];

        array_push($data, $dataTemporary);
    }

then I've tried several ways, one of which is using php Spread Operators

    function merge($data, ...$userIds)
    {
        return array_merge($data, $userIds);
    }

    $data = [
        'lang' => 'id',
        'is_read' => false,
        'is_count' => false
    ];

    $userIds = Subscriber::pluck('user_id')->toArray();

    merge($data, ...$userIds);

currently, my output like this

[
  {
    "lang" => "id",
    "is_read" => false,
    "is_count" => false,
    0 => "5b0172aa5e4f857ed36c0fb7",
    1 => "581c457addfb68a848d47002"
]

and the output that I want

[
  {
    "lang" => "id",
    "is_read" => false,
    "is_count" => false,
    "user_id" => "5b0172aa5e4f857ed36c0fb7",
   {
    "lang" => "id",
    "is_read" => false,
    "is_count" => false,
    "user_id" => "581c457addfb68a848d47002",
]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire