Home > other >  laravel php array grouping using anather array value
laravel php array grouping using anather array value

Time:12-27

I have a problem with array group. Could you please help me to solve this problem. I want to group acording to the $group array value. For a Example, first Group 01 items & second Group 02 items in the table.

// In Controller
 public $inputs = [0, 1, 2];
 public $item_id = [18, 19, 20], $group = ['Group 01', 'Group 02', 'Group 01'];

//In blead
<tbody >
  @forelse ($inputs  as $key => $value)
   <tr> 
     <td > 
      {{ $group[$value] }} 
     </td>

     <td > 
     {{ $item_id[$value] }} 
     </td>
   </tr>
  @empty
  @endforelse

If Can I want give group name each group strat before first item like topic. Thank you

Edit 01

I am making a Laravel livewire application. In my application, I am adding dynamic inputs and I want to show it my blead view.

enter image description here

As the image, When clicking the No 1, will come popup, Then enter the records and add. it will display in the table such as No 3 & 4. But I want to group them according to the group. No 3 items are the same group No 4 is another group. But in here showing according to the inputs array.

In my controller I did,

public $i = -1;
public $inputs = [];
public $category_ids, $item_id, $group;

public function addLine($i)
    { 
        $i = $i   1;
        $this->i = $i;
        array_push($this->inputs, $i);
    }

CodePudding user response:

You can create a group items array by the following code. It will make a nested array of items for each group then you can use them by looping

$group = ['Group 01', 'Group 02', 'Group 01'];
$item_id = [18, 19, 20];
$group_items= [];
foreach($group as $key => $value) {
    $group_items[$value][] = $item_id[$key];
}

In your blade file

@foreach ($group_items as $group => $items)
   <tr> 
     <td > 
      {{ $group }} 
     </td>

     <td > 
     @foreach ($items as $item)
         {{ $item }}
     @endforeach
     </td>
   </tr>
@endforeach
  • Related