Как использовать каждый элемент массива первым - PullRequest
0 голосов
/ 14 апреля 2019

Я занимаюсь разработкой проектов с Laravel 5.7

У меня есть два массива

Это массивы. Я хочу просмотреть таблицу

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
          ]
]
)

Я хочу, чтобы таблица выглядела как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>

Я много пробовал, но не смог написать правильный цикл foreach.

Первая попытка

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

второй массив в первом массиве для результатаправильно, но другие массивы дают неправильный результат

что я делаю не так

Ответы [ 3 ]

0 голосов
/ 14 апреля 2019

после вашего комментария я понял, что не прочитал ваш вопрос должным образом - мои извинения.

Я думаю, что простым решением было бы для пользователя array_column https://www.php.net/manual/en/function.array-column.php

, тогда вы могли быскажем что-то вроде:

$tableheadings = array(['branch','report','product','cost'])[0];
$tableData = array( 
  [
    'branch' =>['branch.add','branch.delete'],
    'report' =>['report.create','report.list'],
    'product' =>['product.add','product.sell'],
    'cost' =>['cost.add','cost.list']
  ]
);

$table = '<thead>' . 
            implode('',array_map(function($th){return '<th>' . $th . '</th>';},$tableheadings)) 
         . '</thead>';


for($i = 0;$i < sizeof($tableData[0]); $i++) {
      $row = array_map(function($td){return '<td>' . $td . '</td>';},array_column($tableData[0],$i));
      if(sizeof($row) == 0) continue;
        $table .= '<tr>' .implode('',$row)  . '</tr>';
}

    echo '<table>' . $table . '</table>';

Я проверил это на phpfiddle, и он дает желаемый результат, вы можете упростить его, если сможете получить данные в немного лучшем формате (я не увереноткуда вы это взяли)

0 голосов
/ 18 апреля 2019

Я сделал это

спасибо за идею @ jameson2012

найден самый длинный массив до

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

после эхо-индексов $ DelegateType для

и каждое первое значение массива 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>
0 голосов
/ 14 апреля 2019

Можете ли вы попробовать это .. надеюсь, что это работает

@for ($i = $delegateGroup; $i < count($delegateGroup); $i++)
    <td> {{ $delegateGroup[i][0]  </td>
@endfor
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...