What is the meaning of the following line:
$data[0][$row->parentid]['children'][$row->id] = $row->name
From the function:
function getCategoriesNav(){
$data = array();
$this->db->select('id,name,parentid');
$this->db->where('status', 'active');
$this->db->orderby('parentid','asc');
$this->db->orderby('name','asc');
$this->db->groupby('parentid,id');
$Q = $this->db->get('categories');
if ($Q->num_rows() > 0){
foreach ($Q->result() as $row){
if ($row->parentid > 0){
$data[0][$row->parentid]['children'][$row->id] = $row->name;
}
else{
$data[0][$row->id]['name'] = $row->name;
}
}
}
$Q->free_result();
return $data;
}
Where do the children come from, and what is the meaning of:
$row->parentid or $row->name? I don't have any field 'children' in my table, and it's not declared any where. Please help
Thank you in advance,
Mehdy
Update
Sorry if I didn’t explain the question clearly. My question was: what is the meaning of the following line in this function
$data[0][$row->parentid]['children'][$row->id] = $row->name, from where this children come from, and what actual mean by $row->parentid or $row->name? I don’t have any field 'children' in my table, and it’s not declared anywhere, please help me.
Thank you
mehdy
Read the code. If the row from categories has a parent ID, child IDs are added to the array under the parent ID's children element. This is simply taking the result set and converting it into a hierarchy data structure which eliminates repetition in places and makes it easier to traverse.
Update:
Specifically, what is the following line of code doing:
$data[0][$row->parentid]['children'][$row->id] = $row->name;
Your function is looping through your query result set and checking if the current row specifies a parent ID. If it does it append a hash to your array of arrays (your hierarchy).
foreach ($Q->result() as $row) {
Your query result is a collection of row objects. Each object appears to have an attribute for each column being selected in your SQL query. So for your SELECT fields:
$this->db->select('id,name,parentid');
We have:
$row->id
$row->name
$row->parentid
Going back to the original line of code:
$data[0][$row->parentid]['children'][$row->id] = $row->name;
This line is constructing a structure like this:
Array (
[0] => Array ( // $data[0]
[400] => Array ( // $data[0][$row->parentid]
[children] => Array ( // $data[0][$row->parentid]['children']
[53] => Animal // these are from [$row->id] = $row->name;
[54] => Mineral
[55] => Vegetable
)
)
[401] => Array (
[children] => Array (
[4] => Wood
[6] => Metal
[2] => Plastic
)
)
)
)
You could simplify this structure slightly by removing the first wrapper array $data[0]. So you'd change the code like so:
$data[$row->parentid]['children'][$row->id] = $row->name;
This changes the structure like so:
Array (
[400] => Array ( // $data[$row->parentid]
[children] => Array ( // $data[$row->parentid]['children']
[53] => Animal // these are from [$row->id] = $row->name;
[54] => Mineral
[55] => Vegetable
)
)
[401] => Array (
[children] => Array (
[4] => Wood
[6] => Metal
[2] => Plastic
)
)
)
I hope this clarifies the code for you.
It add a value in a array namely $row->name with the ID $row->id
So what it does is adding a child row to the parent with the ID that is in $row->parentid at that moment. It loops through the loop and add child's to the parent if the parent has child's
Related
How can I store multiple form array data in laravel, as I need to create a new record against each array index.
[0] => Array
(
[make] => test
[model] => XYZ
)
[1] => Array
(
[make] => s4
[model] => BB
)
[2] => Array
(
[make] => 99
[model] => AX
)
This is what I am trying to, but here loop get executed 6 times instead of three
$results = $request->all();
foreach ($results as $key => $value) {
echo $key;
// insert operation
}
I believe you should specify the control/field because the Request contains other (non-data) information. Something like:
$results = $request['array_name'];
https://laravel.com/docs/5.4/queries#inserts
Model::insert($request->all())
This will mass insert each array into your database. insert do not automatically set datetime values for created_at and updated_at, note that the array keys should match your table columns, and make sure your model has these fields as $fillables.
it's a WHY-question, not How-to one:)
I have assigned a Query Bulder to a variable $query:
$query = table::where(['id'=>1, 'this_version'=> 1]);
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
outputs array with 2(!) sub-arrays:
Array
(
[slug1] => Array
(
[0] => Array
(
[tourist_id] => 1
[tourist_version] => 1
)
[1] => Array
(
[tourist_id] => 2
[tourist_version] => 1
)
)
)
But if I add another line using $query between my $query declaration and it's usage in getting $version[2] array, my $version[2] output is shortened to a 1-dimensional array:
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
// Added line:
$versions['slug0'] = $query->select('version_created')->first()->version_created;
//
$versions['slug1'] = $query->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
outputs (note slug1 now has only 1 nested array):
Array
(
[slug0] => 2017-08-08 08:25:26
[slug1] => Array
(
[0] => Array
(
[tourist_id] => 1
[tourist_version] => 1
)
)
)
it seems like the like this line:
$versions['slug0'] = $query->select('version_created')->first()->version_created;
has added "first()" method to the original $query . Am I right and, if yes, why does it happen?
Well, this is because by default an object (in your case is the Query builder object) in PHP is passed by reference. You can read more about this here: PHP OOP References.
I quote from the above reference:
A PHP reference is an alias, which allows two different variables to
write to the same value.
When you pass the query builder object to the $query variable, you actually just pass the reference to this object and not the copy of it.
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
So when you call the first() method on the second line, it actually modifies the query builder object.
$versions['slug0'] = $query->select('version_created')->first()->version_created;
Thus causing the upcoming query result to be limited to 1. In order to work around this issue, you can clone the query object like this:
$query = previoustour2_tourist::where(['tour2_id'=>$tour->id, 'this_version'=> 1]);
$versions['slug0'] = (clone $query)->select('version_created')->first()->version_created;
$versions['slug1'] = (clone $query)->select('tourist_id', 'tourist_version')->get()->toArray();
print_r($versions);
Hope this help!
I have array i want insert into the values in database using codeigniter, i don't know how to insert , i trying but i am not able to get the answer
My model
print_r($subjectHandling);
Array
(
[subjectId] => Array
(
[0] => 1
[1] => 2
)
)
now i want insert the values in database in this values.
I am trying like this
foreach($subjectHandling as $key=>$value) {
$reg_dat = array(
'statffId' => '1',
'subjectId' => $value,
);
$this->db->insert("subject_handling" , $reg_dat);
}
I m getting error ** Array to string conversion** , so how do this. i want to insert two roes in databse
This should work
$subjectHandling['subjectId'] = array(1, 2);
$reg_dat = array();
foreach($subjectHandling['subjectId'] as $key => $value) {
$reg_dat[] = array('staffId'=> 1, 'subjectId' => $value);
}
$this->db->insert_batch('subject_handling', $reg_dat);
https://www.codeigniter.com/userguide3/database/query_builder.html#inserting-data
I have a from which lists several items that can be selected by check box and a dropdown permitter added. In a separate part of the form is have another check box. This is submitted as two arrays.
The arrays look like this
Array
(
[1] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 1
)
[2] => Array
(
[num_copy] => 1
[dwg_rev] => B
[dwg_id] => 2
)
)
Array
(
[1] => Array
(
[client_id] => 1
)
)
I need to pass these two arrays to a form_validation that can check is dwg_rev has already been added to the database for the selected client_id.
I tried to use is_unique, but it can only check in one table to see if this already exists in it.
This is what my form validation currently looks like
$rows = array();
if(!empty($_POST['result']))
{
$rows = $_POST['result'];
$temp_dwg_array = array_column($rows, 'temp_dwg_id');
foreach($temp_dwg_array as $key => $temp_dwg_id)
{
$this->form_validation->set_rules('result['.$temp_dwg_id.'][dwg_rev]', 'Revision' , 'required|callback_check_issued_rev');
}
} else $this->form_validation->set_rules('result[][temp_dwg_rev]', 'Revision' , 'required');
if(!empty($_POST['client']))
{
$temp_client_array = array_column($_POST['client'],'client_id');
foreach($temp_client_array as $key => $client_id)
{
$this->form_validation->set_rules('client['.$client_id.'][client_id]', 'Please make a selection from the distribution list' , 'required|callback_check_issued_rev');
}
}
else $this->form_validation->set_rules('client[][client_id]', 'Distribution' , 'required');
I want to create a callback function, but I can't figure out how to pass two variables to the callback function to compare to the db.
I have a backend where I can create a Poll. Within a Poll I can create a PollQuestion. And for a PollQuestion, I can create many PollAnswer's.
If I do something like this in my Controller
$poll = DB::table('poll')->orderBy('id', 'desc')->first();
$question = DB::table('poll_question')->where('poll_id', $poll->id)->first();
$answers = DB::table('poll_answer')->select('answer')->where('question_id', $question->id)->get();
print_r("<pre>");
print_r($answers);
print_r("</pre>");
I can see an output like the following
Array
(
[0] => stdClass Object
(
[answer] => Answer 1
)
[1] => stdClass Object
(
[answer] => Answer 2
)
[2] => stdClass Object
(
[answer] => Answer 3
)
[3] => stdClass Object
(
[answer] => Answer 4
)
)
So, the above Poll was given 4 possible answers to the PollQuestion.
Now I have a frontend which displays the question, and a radio button for each PollAnswer. When they select one and save, I get a PollResponse. If I do something like this
$pollResponses = DB::table('poll_response')->select('response')->where('poll_id', $poll->id)->get();
The output might be something like this
Array
(
[0] => stdClass Object
(
[response] => Answer 1
)
[1] => stdClass Object
(
[response] => Answer 4
)
[2] => stdClass Object
(
[response] => Answer 4
)
[3] => stdClass Object
(
[response] => Answer 2
)
[4] => stdClass Object
(
[response] => Answer 3
)
)
So I can see what people have selected. Now, for each possible PollAnswer, I need to count the number of PollResponse which relate to it. So for the above data, I should get something like
1 = 1
2 = 1
3 = 1
4 = 3
Is there any easy way I can do this in Laravel, or would I need to loop both the Answers and Responses to get the individual counts?
I don't know of any laravel-specific solution, but you can always push the responses to a separate array and then use the php function array_count_values($array) (http://php.net/manual/en/function.array-count-values.php) on the new array.
$newArray = array();
for($i=0; $i < count($pollResponses); $i++){
array_push($newArray, $pollResponses[$i]->response);
};
$count = array_count_values($newArray);
It will return a two dimensional array with the answer as the key and the number of times it occurs as the value.
Assuming that you're using models,you can do this in Laravel
$polls = Poll::with(['questions.answers'])->get();
Your Poll.php file
...
class Poll extends Model{
public function questions(){
return $this->hasMany(Question::class);
}
}
Your Question.php file
...
class Question extends Model{
public function answers(){
return $this->hasMany(Answer::class);
}
}
And then in your view file (assuming it's .blade.php)
#foreach($polls as $poll)
#foreach($poll->questions as $question)
{{ $question->title }}
<ul>
#foreach($question->answers as $answer)
<li>{{ $answer->title }} </li>
#endforeach
</ul>
#endforeach
#endforeach