Search code examples
phplaravel-5.7

How to use every array first item


I'm developing projects with Laravel 5.7

I have two arrays

This arrays I want to view table

array(['branch','report','product','cost']);

array( 
[
       'branch' =>
          [
            'branch.add',
            'branch.delete, 
          ]
       'report' =>
          [
            'report.create',
            'report.list,  
          ]
       'product' =>
          [
            'product.add',
            'product.sell'
          ]
       'cost' =>
          [
            'cost.add',
            'cost.list
          ]
]
)

I want the table to look like this

<table>
   <thead>
      <th>Branch</th>
      <th>Report</th>
      <th>Product</th>
      <th>Cost</th>
   </thead>
   <tbody>
     <tr>
        <td>branch.add</td>
        <td>report.create</td>
        <td>product.add</td>
        <td>cost.add</td>
     </tr>
     <tr>
        <td>branch.delete</td>
        <td>report.list</td>
        <td>product.list</td>
        <td>cost.list</td>
     </tr>
   </tbody>
</table>

I tried a lot, but I couldn't write the right foreach loop.

First try

<table>
    <thead>
    <tr>
        @foreach($delegateGroup as $group)
            <th>{{$group}}</th>
        @endforeach
    </tr>
    </thead>
    <tbody>
        @foreach($delegateType as $delegate)
                @foreach($delegate as $v)
                    <tr>
                        <td>{{$v}}</td>
                    </tr>
                @endforeach
        @endforeach
    </tbody>
</table>

second array in first array for result correct but other arrays result wrong

what am I doing wrong


Solution

  • I did it

    thanks for @jameson2012 idea

    finded longest array before

    $rowCount = 0;
    array_walk($delegateType, function ($items) use (&$rowCount) {
                $count = count($items);
                if ($count > $rowCount)
                    $rowCount = $count;
            });
    

    after $delegateType echo indexs for

    and every array first value echo

    <table>
        <thead>
        <tr>
            @foreach(array_keys($delegateType) as $group)
                <th>
                    @if(isset($group))
                        $group
                    @endif
                </th>
            @endforeach
        </tr>
        </thead>
        <tbody>
            @for ($i = 0; $i < $rowCount; $i++)
                <tr>
                @foreach($delegateType as $group => $values)
                    <td>
                        @if(isset($values[$i]))
                              {{$values[$i]}}
                        @endif
                    </td>
                @endforeach
                </tr>
            @endfor    
        </tbody>