I want to work on a while loop in a foreach loop but I can't convert it to Laravel controller system. Please help.
foreach (range('a', 'z') as $i)
{
echo $i = strtolower($i);
$sql = "SELECT * FROM `list` Where name like '$i%' Limit 30";
$result = mysqli_query($con, $sql);
echo"<hr><h3>Name Starting with ".strtoupper($i)."</h3>";
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$id = $row['id'];
$name = $row['name'];
echo "<li>".$row['name']."</li>";
}
echo "<li>More</li>";
echo "</ul>";
}
The code in Laravel that I have is
foreach (range('a', 'z') as $i)
{
$list = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
return view('pages.all', ['list' => $list]);
}
This code only gives data for names starting with alphabet "a" but won't proceed with the rest of the characters.
Store it on the array based on your search.
$list = array();
foreach (range('a', 'z') as $i) {
$list[$i] = DB::table('list')->where('name', 'LIKE', $i.'%')->limit(30)->get();
}
return view('pages.all', ['list' => $list]);
Customize your view, to showing the list against each character (a-z).
[Edit]
View file can be changed like below,
#foreach ($list as $keyI => $moredata)
<hr>
<h3>Author's Name Starting with "{{strtoupper($keyI)}}"</h3>
<ul class="tags-list">
#foreach ($moredata as $data)
<li>{{$data->name}}</li>
#endforeach
</ul>
#endforeach
Related
i'm try to foreach inside the foreach to get the count data with this code
Controller.php
$jadwals = DB::table('tb_jadwal')->get();
foreach ($jadwals as $key => $jadwal) {
$tgl = date("Y-m-d", strtotime($request->tgl));
$cek_tiket = array();
$cek_tiket = DB::table('tb_tiket')
->select(DB::raw('count( distinct id_tiket) as jumlah_kapasitas'))
->where('Tgl_Berangkat', '=', "'$tgl'")
->where('id_jadwal', '=', $jadwal->id_jadwal)
->get();
$jadwals[$key]->jumlah_kapasitas = $cek_tiket;
}
view.blade.php
#foreach($cek_tiket as $cek_tiket)
<?php
if ($cek_tiket->jumlah_kapasitas <= 70) {
echo "There data";
dd($cek_tiket);
}
?>
#endforeach
but the result of dd is 0
My data set and coding are listed below.
[
{
"color":[
{
"id":1,
"color":"yellow"
},
{
"id":2,
"color":"red"
}
]
},
{
"color":[
{
"id":3,
"color":"blue"
},
{
"id":4,
"color":"green"
}
]
}
]
#foreach ($items as $item)
#foreach($item->color as $color)
<p>{{$color->color}}</p>
#endforeach
#endforeach
What I want:
yellow 1/4
red 2/4
blue 3/4
green 4/4
How can I count the total in every row?
First you need to take an array :
#php
$color_counts = array();
#endphp
Than in for loop you can count colors#foreach ($items as $item)
#foreach($item->color as $color)
#php
if(isset($color_counts[$color->color]) && $color_counts[$color->color]!=null){
$color_counts[$color->color]['count'] += 1;
}
else {
$color_counts[$color->color]['count'] = 1;
$color_counts[$color->color]['color_name'] = $color->color;
}
#endphp
#endforeach
#endforeach
Now you can get colors and its count in $color_counts array.
Note : You can do this thing in a controller and pass it to view
you can You Laravel collection count method
$collection = collect([1, 2, 3, 4]);
$collection->count();
like that
for more information follow this link :
https://laravel.com/docs/5.8/collections#method-count
I created a similar JSON code just to show you the way of how to make it work.
[{"id":1,"color":"blue"},{"id":2,"color":"red"},{"id":3,"color":"red"},{"id":4,"color":"green"},{"id":5,"color":"red"},{"id":6,"color":"blue"}]
$colors = Color::all(); // Model contains 6 random colors
$countAllColors = count($colors);
$colorNames = $colors->countBy('color');
foreach ($colorNames->all() as $key => $value) {
$values = $key . $value . '/' . $countAllColors . "\n";
echo $values; // output will be: blue2/6 red3/6 green1/6
}
you might noticed that I'm using countby method to see how much do we have repeated color item in the array.
however, if you want to do it in blade template, just copy the code below and paste it in your blade template
#php
$colors = '[{"id":1,"color":"blue"},{"id":2,"color":"red"},{"id":3,"color":"red"},{"id":4,"color":"green"},{"id":5,"color":"red"},{"id":6,"color":"blue"}]';
$colors = json_decode($colors, true);
$colors = collect($colors);
$countAllColors = count($colors);
$colorNames = $colors->countBy('color');
#endphp
<div>
#foreach ($colorNames->all() as $key => $value)
<b> {{ $key . $value . '/' . $countAllColors .' ' }} </b> <br>
#endforeach
</div>
output
blue2/6
red3/6
green1/6
for the nesting problem, you might want to take a look of this pulck method.
I hope you find it useful
I use the following code to get data from two related tables:
$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;
$subcategories = $objectModel::with("translate", "parent")->get();
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
array_unshift($arr, 'Select category');
return $arr;
In result this part of code I get array with key => value to insert this in select list in Blade template.
But I desire to escape a loop:
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
And get clear collection from request. How can I do it?
You can use Laravel Collections https://laravel.com/docs/5.3/collections
$arr = ProductCategory::with("translate", "parent")->get()
->mapWithKeys(function ($item, $key) {
return [$item->translate()->first()->objectId => $item->translate()->first()->name];
})
->all();
My model:
function get_data($id)
{
$this->db->select('id, Company, JobTitle');
$this->db->from('client_list');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
}
I want to get the the data from get_data(), is this the right way?
public function show_data( $id )
{
$data = $this->get_data($id);
echo '<tr>';
echo '<td>'.$data['Company'].'</td>';
echo '<td>'.$data['JobTitle'].'</td>';
echo '<td>'.$data['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
Use the row_array() function to get the data in the array format.
Reference url
http://ellislab.com/codeigniter/user-guide/database/results.html
you can use foreach loop to print
foreach ($data->result() as $row)
{
echo '<tr>';
echo '<td>'.$row['Company'].'</td>';
echo '<td>'.$row['JobTitle'].'</td>';
echo '<td>'.$row['id'].'</td>';
echo '<td></td>';
echo '</tr>';
}
thank you
just to improve answer, I use "general_model" for all my controllers, there are some exceptions where I need special queries, I just create desired model so "general_model" stays same and I can use it in any project.
e.g.
general_model.php
function _getWhere($table = 'table', $select = 'id, name', $where = array()) {
$this->db->select($select);
$q = $this->db->get_where('`'.$table.'`', $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
.
.
.
//bunch of another functions
in controller I just call
$this->data['books'] = $this->general_model->_getWhere('book', '*', array('active' => '1'));
$this->render('book_list_view'); // $this->load->view('book_list_view', $this->data);
sidenote: I am extending CI_Controller therefore I use $this->data['books'] instead $data['books'] to pass data into view
in view
//check if there are any data
if ($books === FALSE) {
//some error that there are no books yet
} else {
//load data to table or something
foreach ($books as $book) {
$book->id; // book id
}
}
Hi. I have the form in which I use form_validation If the user make any mistake (leave some required fields empty), user is redirected back to the form, and the form has been re-populated. All works, except my select , which is generated from the database.
Here is my code from the view:
echo "<select name='parentid'" . set_value("parentid"). ">";
echo '<option value = "0">None</option>';
foreach ($faq_categories as $row => $option) {
echo "<option value=" . $option['catid'] . ">" . $option['categoryname']. "</option>";
}
echo '</select>';
Here is my controller code:
public function displayAddFaqCategoryForm($error = null)
{
$data['title'] = "Add new FAQ Category";
$data['main_content'] = 'addFaqCategory';
$selectWhat = array('tname' => 'faq_categories',
'sortby'=> 'catid',
'how' => 'asc'
);
$this->load->model('selectRecords');
$data['faq_categories'] = $this->selectRecords->selectAllRecords($selectWhat);
$this->load->vars($data);
$this->load->view('backOffice/template');
} // end of function displayAddFaqCategoryForm
And here is the model code:
public function selectAllRecords($selectWhat = array())
{
$data = array();
$tname = $selectWhat['tname'];
$sortby = $selectWhat['sortby'];
$how = $selectWhat['how'];
$this->db->order_by($sortby,$how);
$query = $this->db->get($tname);
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
} // end of function selectAllRecords
I am not getting any error messages, just the select is not repopulated with last used. Any help will be deeply appreciated.
You're using set_value() incorrectly
echo "<select name='parentid'" . set_value("parentid"). ">";
It's meant to output the actual value (for text inputs). This would produce something like:
<select name='parentid'ActualValue>
Which is not how a <select> element is populated, and is invalid HTML. See the correct usage in the Form Helper docs.
You can use set_select(), and it goes on your <option>:
foreach ($faq_categories as $row => $option) {
echo "<option value=".form_prep($option['catid']).'"';
echo set_select('parentid', $option['catid']); // outputs selected="selected"
echo ">".html_escape($option['categoryname'])."</option>";
}
I've taken a few other liberties with your code here as you can see, to be on the safe side (always).
If this is too much of a mess, you might be interested in the form_dropdown() function.