This is my code
$dataSet = [];
foreach ($answers as $index => $answer) {
$dataSet[] = [$answer->formfield => $answer->answer];
}
dd($dataSet);
Here is how it looks:
array:14 [▼
0 => array:1 [▼
"BC_NC_USCIS_NAME1" => "KIMBERLY JAX SMITH"
]
1 => array:1 [▼
"Birth_name_styled_in_upper_case_lower_case" => "Kimberly Jax Smith"
]
2 => array:1 [▼
"Name_of_the_Trust_2" => "KJSmith, LLC."
]
3 => array:1 [▼
"FIRST_NAME_MIDDLE_INITIAL_LAST_NAME3" => "KIMBERLY J SMITH"
]
4 => array:1 [▶]
5 => array:1 [▶]
6 => array:1 [▶]
7 => array:1 [▶]
8 => array:1 [▶]
9 => array:1 [▶]
10 => array:1 [▶]
11 => array:1 [▶]
12 => array:1 [▶]
13 => array:1 [▶]
]
Here is what I need it to look like
array:8 [▼
"BC_NC_USCIS_NAME1" => "David"
"FIRST_NAME_MIDDLE_INITIAL_LAST_NAME1" => "Patrick"
"LAST_NAME_FIRST_NAME_MIDDLE_NAME_1" => "Smith"
"Current_Address" => "2042 E Quince St"
"Birth_name_styled_in_upper_case_lower_case" => "DAVID PATRICK SMITH"
"Current_City" => "Mesa"
"Current_State" => "AZ"
"Current_Zip_Code" => "85213"
]
Please help if you can! I am banging my head against the wall trying to figure it out.
CodePudding user response:
Just do the following and assign value to the particular key instead of array.
$dataSet = [];
foreach ($answers as $index => $answer) {
$dataSet[$answer->formfield] = $answer->answer;
}
dd($dataSet);
CodePudding user response:
I would use the pluck functionality that Collections offer (as this is exactly what pluck is for). If $answers is a Collection:
$answers->pluck('answer', 'formfield')
If $answers is an array then make a Collection from that array:
collect($answers)->pluck('answer', 'formfield')
That would give you a list that is keyed by 'formfield' with the values being the value of the 'answer' property/attribute.
If you want an array from the Collection just call toArray() on the Collection.
Also, pluck exists on Query Builder, so you can get your list from the database directly if that is where that data had come from:
DB::table(...)...->pluck('answer', 'formfield')
Or via Eloquent:
Model::...->pluck('answer', 'formfield')
Laravel 8.x Docs - Collections - Available Methods - pluck
Laravel 8.x Docs - Collections - Available Methods - toArray
Laravel 8.x Docs - Database: Query Builder - Retrieving A List Of Column Values pluck
