Set key array without loop with Spread Operator in php

Viewed 650

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",
   }
]
2 Answers

You could use various methods (and still think a foreach is a good way of doing it), this just uses array_map() to add the new data into a predefined array...

$userIds = Subscriber::pluck('user_id')->toArray();
$data = array_map(function ($id) { 
    return [
        'lang' => 'id',
        'is_read' => false,
        'is_count' => false,
        "user_id" => $id
    ];
},$userIDs);

echo json_encode($data);

Thank you for helping @Nigel Ren, maybe the code is more appropriate:

$userIds = Subscriber::pluck('user_id')->toArray(); 
$data = array_map(function ($id) {  
return 
   (object)[ 
    'lang' => 'id', 
    'is_read' => false, 
    'is_count' => false, 
    "user_id" => $id 
   ]; 
},$userIDs); 

echo($data);
Related