2

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.

4
  • does the child level is fixed or it may go to next level too ? Commented Jul 21, 2018 at 5:12
  • the child level is not fix, it can be unlimited Commented Jul 21, 2018 at 5:19
  • What @rkj means: is it limited to Face Make Up > Foundation or can you have something like Face Make Up > Foundation > Red > With sparkles? Commented Jul 21, 2018 at 6:56
  • yes it can be like this Face Make Up > Foundation > Red > With sparkles Commented Jul 21, 2018 at 7:19

2 Answers 2

3

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

3 Comments

Alhamdulillah. TQVM
This will not work for items nested deeper than your two loops. OP stated the child level is not fixed.
Hi, @softboxkid I updated my answer following the issue access deeper items dynamically. Thanks @Joseph_J for your comment.
0

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>';

1 Comment

@softboxkid The first answer that was provided will only go as deep into the array as their are loops provided. The function above will go through the array recursively and provide all items regardless of how far down they are.

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.