Skip to content

Instantly share code, notes, and snippets.

@mayoz
Created April 11, 2014 20:16
Show Gist options
  • Save mayoz/10498070 to your computer and use it in GitHub Desktop.
Save mayoz/10498070 to your computer and use it in GitHub Desktop.
Convert single dimensional array with optional parameters (Laravel Form::select)
<?php
// Test data
$categories = array(
array(
'title' => 'Cats',
'value' => 1,
'children' => array(
array(
'title' => 'Leopard',
'value' => 2,
'children' => array(
array(
'title' => 'Small',
'value' => 9
),
array(
'title' => 'Big',
'value' => 10
),
),
),
),
),
array(
'title' => 'Dogs',
'value' => 3,
'children' => array(
array(
'title' => 'Spaniel',
'value' => 4,
),
),
),
array(
'title' => 'Octopus',
'value' => 5,
),
array(
'title' => 'Horse',
'value' => 6,
),
array(
'title' => 'Mouse',
'value' => 7,
),
array(
'title' => 'Chicken',
'value' => 8,
),
);
// Use Laravel 4 Form::select
echo Form::select('animal', ['' => 'Select...'] + array_lists($categories));
echo Form::select('animal', ['' => 'Select...'] + array_lists($categories), 5);
echo Form::select('animal', ['' => 'Select...'] + array_lists($categories, ['repeat' => 2, 'delimiter' => '-']), 8, ['id' => 'categories', 'class' => 'form-control']);
<?php
// 1. create app/helpers.php
// 2. include in app/start/global.php
// 3. Write and use
/**
* Convert single dimensional array with optional parameters
*
* @author Sercan CAKIR <[email protected]>
* @param array $array
* @param array $options
* @param int $level
* @return array
*/
function array_lists(array $array = array(), array $options = array(), $level = 0)
{
$data = [];
$repeat = array_get($options, 'repeat', 2);
$delimiter = array_get($options, 'delimiter', '&nbsp;');
foreach($array as $key => $value)
{
$data[$value['value']] = str_repeat($delimiter, $level * $repeat) . $value['title'];
if (is_array(array_get($value, 'children')))
{
$data += array_lists($value['children'], $options, $level + 1);
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment