softboxkid
softboxkid

Reputation: 908

Generate dropdown with optgroup from PHP array

I am creating an e-commerce website using laravel. I have a problem to generate dropdown select from set of array. Below is the array:

array(

 [0] => Array
    (
        [name] => Women's Clothing
        [id] => 16
        [parentid] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [name] => Tops
                        [id] => 411
                        [parentid] => 16
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Blouse
                                        [id] => 6556
                                        [parentid] => 411
                                    )

                                [1] => Array
                                    (
                                        [name] => Crop Tops
                                        [id] => 6557
                                        [parentid] => 411
                                    )

                            )

                    )

                [1] => Array
                    (
                        [name] => Women's Outerwear
                        [id] => 2262
                        [parentid] => 16
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Sweaters
                                        [id] => 6570
                                        [parentid] => 2262
                                    )

                                [1] => Array
                                    (
                                        [name] => Cardigans
                                        [id] => 6571
                                        [parentid] => 2262
                                    )

                            )

                    )
          )
)
[1] => Array
    (
        [name] => Health & Beauty
        [id] => 129
        [parentid] => 0
        [children] => Array
            (
                [0] => Array
                    (
                        [name] => Face Make Up
                        [id] => 2450
                        [parentid] => 129
                        [children] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Powder & Compacts
                                        [id] => 6616
                                        [parentid] => 2450
                                    )

                                [1] => Array
                                    (
                                        [name] => Foundation
                                        [id] => 6617
                                        [parentid] => 2450
                                    )

                            )

                    )
          )
  )

)

How to generate dropdown select from this set of array to be like this:

<select name='select_name'>
  <option value="">-- please select --</option>
  <optgroup label="Women's Clothing"></label>
    <option value="6556">Tops > Blouse</option>
    <option value="6557">Tops > Crop Tops</option>
    <option value="6570">Women's Outerwear > Sweaters</option>
    <option value="6571">Women's Outerwear > Cardigans</option>
  <optgroup label="Health & Beauty"></label>  
    <option value="6616">Face Make Up > Powder & Compacts</option>
    <option value="6617">Face Make Up > Foundation</option>
</select>

Looking to the array itself, all the parentid=0 should be place in optgroup of the form select. Now the challenge part for me is, how to loop the child's name and append '>' symbol and loop until the last child. The option value should be the last child id. Please help. I really had no idea how to solve my problem.

Upvotes: 2

Views: 1087

Answers (2)

Md Nasir Fardoush
Md Nasir Fardoush

Reputation: 820

Here is two way you can generate a drop down list in your laravel blade.

#First way(Access items static way)

<select name='select_name'>
 <option value="">-- please select --</option>
    @foreach($data_array as $parents){ //$data_array is your original array

      <optgroup label="{{ $parents['name'] }}">

        if(is_array($parents['children'])){

            foreach($parents['children'] as $children){

                if(is_array($children['children'])){

                    foreach($children['children'] as $items){
                      <option value="{{ $items['id'] }}">{{ $children['children']['name'] }} > {{ $items['name'] }}</option>
                    @endforeach
                 @endif
            @endforeach
        @endif

       </optgroup>
    @endforeach
</select>

#Second way(Access items dynamic way)

If items are more nested you can simply do this using function recursion.

Make dropdownlist in controller

 <?php

......
.......
class TestController extends Controller
{
    public $names = ""; //Sub category names
    public $dropdownList = ""; //options dropdown list

    public function index()  //function call using route
        {
            $dropdownlist = $this->getLastChildren($items_array,1);
            return view('index', compact('dropdownlist'));
        }
    //make dropdown list 
    public function getLastChildren($items,$parent=0){
        foreach($items as $item){
            if($parent == 1){  //set optgroup title
                $this->dropdownList .= "<optgroup label=".$item['name'].">";
                $this->names = '';
            }
            if(isset($item['children']) && is_array($item['children'])){
                if(!empty($item['name']) && $parent == 0){
                    $this->names .=$item['name'].'>'; //set subcategory names
                }
                $this->getLastChildren($item['children'],0); //call this function recursively for get last children
            }else{ 
                // Confirm it's last item
                $this->dropdownList .="<option value=".$item['id'].">".$this->names.$item['name']."</option>";
            }
            if($parent == 1){
                $this->dropdownList .= "</optgroup>";
            }

        }
        return $this->dropdownList; //return dopdown list
      }


}

In blade file simply print this dropdownlist

<select>
       <option value=''>-- please select --</option>
        {!! $dropdownlist !!} //list from controller
</select>

Upvotes: 3

Joseph_J
Joseph_J

Reputation: 3669

Based off of your comment that the depth of the child elements are not known, the only way to do this is recursively with a callback function.

Try out this code below.

function getChildren($array, $category = NULL){  

  foreach($array as $child){

    if(isset($child['children']) && $child['children']){

      if($category != NULL){

        $newCategory = $category . ' > ' . $child['name'];

      }else {

          $newCategory = $child['name'];

        }

      getChildren($child['children'], $newCategory);

    } else {

      echo '<option value="' . $child['id'] . '">' . $category . ' > ' . $child['name'] . '</option>';

    }

  }

  unset($category);

}


echo
'<select name="select_name">
  <option value="">-- please select --</option>';

  for($i = 0; $i < count($array); $i++){

    echo
    '<optgroup label="' . $array[$i]['name'] . '"></label>';

    getChildren($array[$i]['children']);    

  }

echo
'</select>';

Upvotes: 0

Related Questions