php - how to changes the values of an array of objects based on another object in laravel?
first of all sorry for the poor English. I want to change the values of an array of objects based on a map array. let me explain it with an example:
$map = {
"name": "esm",
"type": "noe",
};
$data = {
"Sheet1":
[
{
"id": 2,
"esm": "omid1",
"noe": "pdf1",
"address": "a/b/omid.pdf1"
},
{
"id": 3,
"esm": "hanie1",
"noe": "jpg1",
"address": "a/b/hanie.jpg1"
},
{
"id": 4,
"esm": "habib1",
"noe": "doc1",
"address": "a/b/habib.doc1"
},
{
"id": 5,
"esm": "sina1",
"noe": "txt1",
"address": "a/b/sina.txt1"
}
],
"Sheet2":
[
{
"id": 2,
"esm": "omid2",
"noe": "pdf2",
"address2": "a/b/omid.pdf2"
},
{
"id": 3,
"esm": "hanie2",
"noe": "jpg2",
"address2": "a/b/hanie.jpg2"
},
{
"id": 4,
"esm": "habib2",
"noe": "doc2",
"address2": "a/b/habib.doc2"
},
{
"id": 5,
"esm": "sina2",
"noe": "txt2",
"address2": "a/b/sina.txt2"
}
]
}
as you can see the $data has 2 sheets(actually data of an excel file) each has some records and the $map has 2 records that map columns of the sheets to database table columns. I want to create an array of objects with those records of the $data that exists in the $map. something like this:
$result = [
{
"name": "omid1",
"type": "pdf1"
},
{
"name": "hanie1",
"type": "jpg1"
},
{
"name": "habib1",
"type": "doc1"
},
{
"name": "sina1",
"type": "txt1"
},
{
"name": "omid2",
"type": "pdf2"
},
{
"name": "hanie2",
"type": "jpg2"
},
{
"name": "habib2",
"type": "doc2"
},
{
"name": "sina2",
"type": "txt2"
},
]
I did myself some work on it but I used 3 for loops that is not an appropriate way to handle it. please guide me here :)
this is my attempt but it doesn't works correctly:
$uploads = (new FastExcel)->withSheetsNames()->importSheets($request->path);
$sheets = $request->sheets;
$table = $request->table_name;
$maps = $request->map;
foreach ($sheets as $sheet) {
if(isset($uploads[$sheet])) {
$records = $uploads[$sheet];
foreach ($records as $record => $record_value) {
foreach ($maps as $map => $value) {
$maps[$map] = $record[$value];
}
$records[$record] = $record_value;
}
}
}
return $records;
for better understanding, I need to import excel files with multi sheets that doesn't match exactly with database table columns so I get a map Array to know use with columns of excel file for each column of database tabale
Answer
Solution:
I used collect
to convert JSON object into a PHP array.
$results = [];
foreach ($sheets as $sheet) {
$uploads = collect($uploads)->toArray();
if (isset($uploads[$sheet])) {
$records = $uploads[$sheet];
foreach (collect($records)->toArray() as $record) {
$record = collect($record)->toArray();
$result = [];
foreach ($maps as $key => $value) {
$result[$key] = $record[$value];
}
$results[] = $result;
}
}
}
return $results;
Source