Good Day,
I am trying to get a correct ordered value from image above, I expect the value would be like below
2,3,4,5,6,7,8,19,9,20,10,11,12,13...18 (the order is from left top to right bottom)
I use this function below
function getUserEmptyLeg($sponsor_id){
$data_params = array(
":placement_id" => $sponsor_id,
":status" => "aktif"
);
$data = fetchAll("SELECT * FROM users WHERE placement_id =:placement_id AND STATUS=:status", $data_params);
$new_sponsor_ids = array();
$member = array();
foreach($data as $row){
$member[$row['user_id']] = array(
"placement_id" => $row['placement_id'],
"user_id" => $row['user_id'],
"member_name" => $row['username'],
"leg" => $row['leg']
);
$new_sponsor_ids[] = $row['user_id'];
}
foreach($new_sponsor_ids as $new_sponsor_id){
$member = array_merge($member, getUserEmptyLeg($new_sponsor_id));
}
return $member;
}
result from above function
2,3,4,5,8,9,10,11,12,13,14,...18,6,7,19,20
but the result from above function didn't output the result as i expected.
i am trying as best as possible to make my question clear, im sorry if you all confused when answering it. but i need help from you all, thanks.
Related
I have the following function which should return all the tournaments and corresponding rounds inside an array.
When I call the function inside the body using a print_r I get only one tournament and round returned, however there are multiple tournaments and rounds. It is like the loop exits after only one iteration
function getTournaments(){
global $db;
$sql = "SELECT tournament, weekNum
FROM schedule
GROUP BY tournament";
$stmnt = $db->prepare($sql);
$stmnt->execute();
$tournaments = $stmnt->fetchAll();
$data = array();
foreach($tournaments as $tournament){
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
}//foreach
return $data;
}//function
print_r(getTournaments());
Database dump
Here you can see the corresponding mysql statement run on the db
My output / Problem
As you can see on image below I only get one tournament and round returned when doing print_r, why am I not getting all tournaments and rounds returned inside the function array? Am I missing something here?
you over write $data in the loop you want to create new arrays (multidimensional):
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
You should have used $data as an array :)
Use this
$data[] = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
instead of
$data = array('tournament' => $tournament['tournament'], 'round' => $tournament['weekNum']);
This is the first time i create my own webservice (someone always did it for me before), so please bear with me.
I post this array :
$data = array(
'user_id' => $this->post('user_id'),
'group_id' => $this->post('group_id'),
'child_id' => $this->post('child_id'), //will be nested array
'custom' => $this->post('custom'),
'time' => $this->post('time'),
'date' => $this->post('date')
);
I tried to create a nested array with this : $this->post('child_id'), because user can post multiple child_id at once.
Then i tried to iterate through the child_id, because i need to insert them to the mysql :
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
What should i do, so i can have an array of child_id in my $data array? (nested array)
And how to iterate through it?
UPDATE :
I have updated the codes above.
I use advanced rest client for testing, and i tried to post something like this in the form content type :
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
Notice that theres two child_id (left most and right most), but only the last one (right most) is inserted.
And this is the add_trans in the model :
function add_trans($table, $data, $schedule_id) {
$query = $this->db->insert($table, array('child_id' => $data['child_id'], 'schedule_id' => $schedule_id));
return $query;
}
Thanks a lot for your time.
Even thought you set the name attribute as child[] on the markup,
You still need to call it as:
'child_id' => $this->post('child_id')
It will still return an array.
for($i = 0; $i < sizeof($data['child_id']); $i++) {
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
EDIT:
Looking upon you query string, that seems to be the culprit:
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
^ same index , same index, same index, it will overwrite and you will get only `2`
If you want to get them all into an array format, you need to set them like this
child_id[]=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id[]=2
^ it needs to be set like this
UPDATE:
And in your model, if you want each id per row, well you can also loop in this case:
function add_trans($table, $data, $schedule_id) {
foreach($data['child_id'] as $child_id) {
$query = $this->db->insert($table, array('child_id' => $child_id, 'schedule_id' => $schedule_id));
}
// return $this->db->insert_id();
return $query;
}
ofcourse that won't work, it has to be
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data['child_id'][$i], $result_id[0]['id']);
}
because you've not set $data['child_id[]'] so it doesn't exist, the key is just a string or number, it does not validate or parse anything
you don't need to give child[] in post method. just give only child, it will get complete array what are you sending from views
replace
'child_id' => $this->post('child_id[]')
with
'child_id' => $this->post('child_id')
I am making an application using CakePHP. I made an action which uses saveAll function.
And I thought it works well, because it doesn't need so much data, but it took over 3 minutes to save using saveAll, or other save function.
Does anyone find my mistakes?
phpMyadmin's columns:
id, rank, school_detail_id, total_score, school_name,
(there is about 300~400 data)
public function rank_update(){
$check_scores = $this->ClubScore->find('all', array('fields'=>array('id','total_score')));
$check_scores2 = Set::sort($check_scores, "{n}.ClubScore.total_score","DESC");
$rank_id=0;
$temp_score=0;
$temp = null;
$for_count=0;
foreach ($check_scores2 as $check_score):
if($temp_score != $check_score['ClubScore']['total_score']){
$rank_id++;
$temp_score = $check_score['ClubScore']['total_score'];
// make ranking by score. same score is same ranking.
}
$this->ClubScore->id = $check_score['ClubScore']['id'];
$this->ClubScore->saveField('rank', $rank_id);
endforeach;
}
Divide the query from foreach to simpler approach
get distinct total_score in desc order
$data = $this->ClubScore->find('all', array('fields'=>array('DISTINCT total_score'), 'order' => 'total_score DESC'));
and then simply save the key as rank for each total_score using updateAll and foreach
Thank you very much Abhishek and AgRizzo ,Nunser!!
Now, I've completely solved this problem. It takes only 1 or 2 seconds!!!!!
Here is the source code.
public function rank_update(){
$data = $this->ClubScore->find('all', array('fields'=>array('DISTINCT total_score'), 'order' => 'total_score DESC'));
$check_scores = $this->ClubScore->find('all', array('fields'=>array('id','total_score')));
$check_scores2 = Set::sort($check_scores, "{n}.ClubScore.total_score","DESC");
$ii = 0;
$temp = 0;
foreach($check_scores2 as $scores):
if($data[$ii]['ClubScore']['total_score']
== $scores['ClubScore']['total_score']){
$temp=$ii+1;
}else{
$ii++;
$temp=$ii+1;
}
$update_arr[] = array(
'ClubScore' => array(
'id' => $scores['ClubScore']['id'],
'rank' =>$temp,
)
);
endforeach;
$update_arr = Set::sort($update_arr, "{n}.ClubScore.id","ASC");
var_dump($update_arr);
foreach($update_arr as $update_arrs):
$this->ClubScore->updateAll(
array(
'ClubScore.rank' => $update_arrs['ClubScore']['rank'],
),
array(
'ClubScore.id' => $update_arrs['ClubScore']['id'],
)
);
endforeach;
}
Thank you very much.
Best regards.
Here is the code:
$the_question = $_POST['question'];
$the_answer = $_POST['answer'];
$dummy_num[] = $_POST['dummy_answer_1'];
$dummy_num[] = $_POST['dummy_answer_2'];
$dummy_num[] = $_POST['dummy_answer_3'];
//Get Hidden Test ID and Q_order
$test_id = $_POST['test_id'];
$q_order = $_POST['q_order'];
//Submit Question
$data_submit_q = array (
'type' => 1,
'question' => $the_question,
'done' => 1
);
$this->db->where('test_id', $test_id);
$this->db->where('q_order', $q_order);
$this->db->update('questions', $data_submit_q);
$question_id = $this->db->insert_id();
$time_created = date('Y-m-d H:i:s');
//Submit Answer
$data_submit_a = array (
'test_id' => $test_id,
'question_id' => $question_id,
'option' => $the_answer,
'company_id' => $data['company']->id,
'job_id' => $data['session_job_id'],
'time_created' => $time_created
);
$this->db->insert('options', $data_submit_a);
$answer_id = $this->db->insert_id();
//Let question know that answer is right.
$data_submit_qr = array (
'answer_id' => $answer_id
);
$this->db->where('id', $question_id);
$this->db->where('test_id', $test_id);
$this->db->update('questions', $data_submit_qr);
Setting the answer id removes the value of the question id, then on updating the database the answer id has no value also. Even though it does right before.
The method $this->db->insert_id() retrieves the ID when performing database inserts (as the name hints).
You're using it after an update, that's why your $question_id gives problems (I think it would be set to FALSE, but I don't know for sure what does that method return when called on the wrong context). WHen you do your last update you use this as a WHERE condition, and if it is not set...
It's not that your second call to insert_id() wipes out the first, I suspect is more like the first one is already NOT SET (or FALSE)
It seems that there is a bug with insert_id, you can try using:
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastInsertId = $row['LAST_INSERT_ID()'];
Hope it helps
I have this code in my model when the controller requests to get all the messages for a certain user:
public function get_messages($user_id) {
$sql = "SELECT *
FROM messages
WHERE `to` = '$user_id'
ORDER BY id DESC";
$query = $this->db->query($sql);
foreach($query->result() as $row) {
$messages[] = array(
'id' => $row->id,
'to' => $row->to,
'from' => $row->from,
'message' => $row->message,
'star' => $row->star,
'timestamp' => $row->timestamp
);
}
return $messages;
}
Here's the code in my controller:
$result = $this->inbox_m->get_messages($user['id']);
How can I return the result as a JSON object using PHP's json_encode() function?
Normally I do something like this for simple returns:
json_encode(array('result' => true))
but all these arrays in arrays got me confused.
EDIT
Never mind guys, should have actually tried it before posting. This works just fine:
echo json_encode(array('result' => $result));
I will close the question in a day when my account allows me.
json_encode($messages); should be fine here. Call it and examine the output to see if it's what you want. But json_encode should handle nested arrays without breaking a sweat.
Closing the question by answering it myself. Like explained in the edit this works just fine:
echo json_encode(array('result' => $result));