John Davidson

php - Map two collections into keys and values

0 comments
Message:


I have Collection A like this...


[
"Gender",
"Name",
"Role",
],

... and I have a Collection B from a model instance like this...


[
App\Models\Staff {
id: 11,
name: "John Doe",
gender: 'Male',
2: "role",
role: App\Models\Role {
id: 1,
name: "Director",
},
},

App\Models\Staff {
id: 22,
name: "Jane Doe",
gender: 'Female',
2: "role",
role: App\Models\Role {
id: 2,
name: "Company Secretary",
},
},
],

How can I get the two combined in a way that I have Collection C like this...


[
[
"Gender" => 'Male',
"Name" => 'John Doe',
"Role" => 'Director',
],
[
"Gender" => 'Female',
"Name" => 'Jane Doe',
"Role" => 'Company Secretary',
],
]

I have tried a few things so far including this as a starting point.


return $collectionB->map(function ($b) use ($collectionA) {
return $collectionA->map(function ($a) use ($b) {
return [
$a => $b['gender'],
$a => $b['name'],
$a => $b['role']['name'],
];
})->all();
})->all();


My Answer:
You can achieve the desired result by iterating over Collection B and mapping the values to keys from Collection A. Here's how you can do it:

php
$collectionC = $collectionB->map(function ($item) use ($collectionA) {
$mappedItem = [];
foreach ($collectionA as $key) {
if ($key === 'Role') {
$mappedItem[$key] = $item->role->name;
} else {
$mappedItem[$key] = $item->$key;
}
}
return $mappedItem;
});

$collectionC = $collectionC->values()->all();


This code snippet will map the values from Collection B to keys from Collection A and create a new Collection C with the desired structure.

Rate this post

5 of 5 based on 1679 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us