0

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.

0

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.