Reputation: 43
I'm getting a problem while I want to loop through an array and display it with Laravel blade engine
My controllers code is like this
$table = DB::table('tables')->select('id')->where('name', strtolower($name))->first();
$columns = Column::where('table_id', $table->id)->get();
foreach ($columns as $col) {
$data[] = $col->col_name;
};
$content = DB::table($name)->select(...$data)->get();
return view('back.group.view-table', compact('content', 'columns', 'data'));
And my blade view code is like this
<table class="table table-striped">
<thead>
<tr>
@foreach($columns as $column)
<th>{{ $column->dis_name }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach ($content as $value)
<tr>
@for ($i = 0; $i < count($columns); $i++)
<td>{{ $value->key = $data[$i] }}</td>
@endfor
</tr>
@endforeach
</tbody>
</table>
This is the result which I get with the following code:
Upvotes: 0
Views: 13383
Reputation: 1
$hayStack = ['name' => 'John', 'age' => 30, 'sex' => 'm'];
$searchValue = 30;
$keyName = array_keys($hayStack, $searchValue)[0];
array_keys() will search all possible keys containing search value. Considering $hayStack
to be an array, there won't be any duplicate key, so our result will be at index 0.
For search value is 30, result will be 'age'.
Here array_keys is an inbuilt function https://www.php.net/manual/en/function.array-keys.php
Upvotes: -1
Reputation: 43
I Found the answer i just change my view from this
<table class="table table-striped">
<thead>
<tr>
@foreach($columns as $column)
<th>{{ $column->dis_name }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach ($content as $value)
<tr>
@for ($i = 0; $i < count($columns); $i++)
<td>{{ $value->key = $data[$i] }}</td>
@endfor
</tr>
@endforeach
</tbody>
</table>
To this
<table class="table table-striped">
<thead>
<tr>
@foreach($columns as $column)
<th>{{ $column->dis_name }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach ($content as $value)
<tr>
@foreach ($data as $key)
<td>{{ $value->$key }}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
Upvotes: 0
Reputation: 28529
use array_keys()
to get all the keys from an array, you also can use foreach($arr as $key => $value)
Upvotes: 0
Reputation: 9381
Another solution would be using array_flip() it will flip the keys and values around.
Upvotes: 1
Reputation: 4756
php has a function called array_keys();
so it looks something like this I think
$results = DB::table($name)->select(...$data)->get();
$content = $results->first();
$keys = array_keys($content->toArray());
this will get you the keys. If you need the keys from each result just loop over $results and for each $result get the keys, using the array_keys syntax.
Upvotes: 4
Reputation: 4547
Change like this
<table class="table table-striped">
<thead>
<tr>
@foreach($columns as $column)
<th>{{ $column->dis_name }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach ($content as $value)
<tr>
<td>{{ $value->name }}</td>
</tr>
@endforeach
</tbody>
</table>
Upvotes: 0