Geoff_S
Geoff_S

Reputation: 5107

Adding multiple object values to array with key names

In Laravel, I'm trying to create an array of some existing values I have that are built from values from a JSON object.

I have the 4 variables set and they dump properly but I'd like to add all 4 (username, perms, roles, access) to the array (IdentifierArray) with their own key/name so that when I add the array to the session and inspect it, I can see each value with it's key/name.

Code at this point:

$IdentifierArray = [];

$Username = $login->username;
$Perms = $login->permissions;
$Roles = $login->roles;
$Access = $login->access;

Session::put('Array of Values', $identifierArray);

So I'd like to add those object values to the array in the best way while having a key for each as well, like:

Array(
    "username": $username value,
    "perms":$perms value,
    "Roles":$roles value,
    "Access":$Access value
)

Upvotes: 0

Views: 947

Answers (3)

piscator
piscator

Reputation: 8709

You can use the array_only helper to make your life easy:

$identifierArray = array_only(
    json_decode($login, true), 
    ['username', 'permissions', 'roles', 'access']
);

Another option would be to use the only() Collection method:

collect(json_decode($login, true))
    ->only(['username', 'permissions', 'roles', 'access'])
    ->all();

Upvotes: 1

Anuga
Anuga

Reputation: 2827

Another way of doing it, equal to @danboh:

$IdentifierArray = [
  "username" => $login->username,
  "permissions" => $login->permissions,
  "roles" => $login->roles,
  "access" => $login->access
];

Upvotes: 3

danboh
danboh

Reputation: 778

Why not use a regular PHP array? Like:

$IdentifierArray["username"] = $login->username;
$IdentifierArray["permissions"] = $login->permissions;
$IdentifierArray["roles"] = $login->roles;
$IdentifierArray["access"] = $login->access;

Upvotes: 1

Related Questions