2

I am very new to PHP, learning fast but not fast enough! I am also learning Laravel 5.1.

I am trying to build a HTML select list array from an Eloquent query output, in the correct format for form builder (Form::select).

I have the following call to Eloquent to pull the data:

// Get list of States for address select
$states = State::all()->toArray();

It returns the following array:

array:8 [▼
  0 => array:2 [▼
    "id" => "1"
    "state" => "ACT"
  ]
  1 => array:2 [▼
    "id" => "2"
    "state" => "NSW"
  ]
  ...
];

I want to loop through it and generate the following output:

array = [
   ''  => 'State',       <-- This is the default for the select list
   '1' => 'ACT',
   '2' => 'NSW',
   ...
];

I am using Laravel 5.1, so I am using the included array_add() function in my helper.

I call my function like this:

$states = create_select_list($states, 'State');

I next want to format the output so it is ready for the Form::select statement. I have tried the code below (as the final try from a few iterations!) but unsuccessfully.

function create_select_list($data, $default)
{
    // Declare array and set up default select item
    $container = ['' => $default];

    // Loop through data entries and build select list array
    foreach($data as list($entry, list($key, $value))) {
        $container = array_add($container, $key, $value);
    }

    // Return the select list array
    return $container;
}

All help or suggestions are appreciated!

1
  • Isn't there some sort of "prompt" option in Laravel's Form::select? Because, that "State" you're trying to add is just a HTML attribute Commented Aug 17, 2015 at 10:02

3 Answers 3

2

This answer is not about loop fix. I think previous comment should help you.

Just another idea. You can try use array_map instead foreach for this case.

For example:

$states = ['' => 'State'];

array_map(function($item) use (&$states) {
    $states[$item['id']] = $item['state'];
}, State::all()->toArray());
Sign up to request clarification or add additional context in comments.

Comments

1

Loop like below:

foreach($data as $key => $keyArr ) {
    $container = array_add($container, $keyArr['id'], $keyArr['state']);
}

Comments

0

You don't need to use list() in your foreach loop, instead try:

foreach($data as $key => $value) {
    $container = array_add($container, $key, $value);
}

The PHP documentation gives a good overview of what list() actually does.

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.