This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 5 years ago.
I have an array like below,
[{
"name":"Daniel",
"connection_status":"1"
},
{
"name":"Danny",
"connection_status":"3"
},
{
"name":"Moris",
"connection_status":"2"
},
{
"name":"Manny",
"connection_status":"1"
}]
I want to sort my array by status like 1,2,3 in this order.
This is my code,
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$query = $this->db->get();
$list = $query->result();
$friends = $this->checkFriends($list, $user_id);
return $friends;
}
public function checkFriends($list, $user_id)
{
$array = [];
foreach ($list as $k => $v) {
// print_r(json_encode($list));
$friends = $this->checkStatus($v->profile_id);
//print_r($friends);
$relationship = '';
$relation_id = '';
foreach ($friends as $kk => $vv) {
if ($user_id == $vv->sent_id) {
if ($vv->status == 1) {
$relationship = 1;
}
if ($vv->status == 2) {
$relationship = 2;
}
} else if ($user_id == $vv->recieved_id) {
// pending
if ($vv->status == 1) {
$relationship = 3;
$relation_id = $vv->sent_id;
}
if ($vv->status == 2) {
$relationship = 4;
}
}
}
$list[$k]->connection_status = $relationship;
$list[$k]->relation_id = $relation_id;
}
return $list;
}
public function checkStatus($id)
{
$this->db->select('*');
$this->db->from('requests');
$this->db->where('sent_id', $id);
$this->db->or_where('recieved_id', $id);
$query = $this->db->get();
$list = $query->result();
return $list;
}
connection status is not a db field.
Where $list is my o/p array.Can anyone help me.Thanks in advance.
I want to sort my array based on my connection_status.
if i understand you correctly this may help you
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$this->db->order_by('status', 'asc');
$query = $this->db->get();
$list = $query->result();
return $list;
}
You can apply order by in query
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$this->db->order_by('status'); // USE ORDER BY
$query = $this->db->get();
$list = $query->result();
return $list;
}
public function getProfileDataForMySociety($user_id)
{
$this->db->select('*');
$this->db->from('profile');
$this->db->where('profile_id!=', $user_id);
$query = $this->db->order('status asc')->get();
$list = $query->result();
return $list;
}
Related
I spent a whole day just to find out, how to make my code cooler. I just curious about, Can I call Codeigniter model function as a table?. Here is codeigniter with my little custom serverside datatables.
my Model : M_global
private function _get_datatables_query($table, $column_order, $column_search, $order) {
$this->db->from($table);
$i = 0;
foreach ($column_search as $item) {
if($_POST['search']['value']) {
if($i===0) {
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if(count($column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if(isset($_POST['order'])) {
$this->db->order_by($column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if(isset($order)) {
$order = $order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables($table, $column_order, $column_search, $order)
{
$this->_get_datatables_query($table, $column_order, $column_search, $order);
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered($table, $column_order, $column_search, $order)
{
$this->_get_datatables_query($table, $column_order, $column_search, $order);
$query = $this->db->get();
return $query->num_rows();
}
public function count_all($table) {
$this->db->from($table);
return $this->db->count_all_results();
}
// My query here
function sum_filter() {
return $this->db->query("
SELECT
main.name,
main.date_submit,
main.id_claim,
ifnull((SELECT SUM(amount) FROM v_t_office
WHERE id_claim = main.id_claim), 0) as total_office,
ifnull((SELECT SUM(amount) FROM v_t_misc
WHERE id_claim = main.id_claim), 0) as total_misc,
ifnull((
(SELECT SUM(amount) FROM v_t_office
WHERE id_claim = main.id_claim) +
(SELECT SUM(amount) FROM v_t_misc
WHERE id_claim = main.id_claim)
), 0) as total_expense
FROM
vc_submit main
GROUP BY main.id_claim
")
}
my Controller : Approval
Here is my problem, I cant use, in $table
public function show_approve() {
$table = $this->M_global->sum_filter(); //Here
// $table = 'v_transaction';
$column_order = array(null, 'name','date_submit','total_office','total_misc','total_expense',null);
$column_search = array('name','date_submit','total_office','total_misc','total_expense');
$order = array('name' => 'asc');
$list = $this->M_global->get_datatables($table, $column_order, $column_search, $order);
$data = array();
$no = $_POST['start'];
foreach ($list as $l) {
$no++;
$row = array();
$row[] = $no;
$row[] = $l->name;
$row[] = date('d-m-Y', strtotime($l->date_submit));
$row[] = $l->total_office;
$row[] = $l->total_misc;
$row[] = $l->total_expense;
$row[] = '';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsFiltered" => $this->M_global->count_filtered($table, $column_order, $column_search, $order),
"recordsTotal" => $this->M_global->count_all($table),
"data" => $data,
);
echo json_encode($output);
}
I can't use
$table = $this->M_global->sum_filter();
The ajax response say "strpos() expects parameter 1 to be string, object given". What am I doing wrong? or Its just cannot. For alternative I use v_transaction table which is made by sum_filter() query.
I'm unable to retrieve similar post data from db with codeigniter. In my blog, I have a tags field which is keeping data like 'php,mysql,mongo,java,jquery'
I just try to get similar post which is related with current posts tags. But im not getting expected result. and the problem is in my query. Its show only three post and that is 1st, last, and number 3rd one.
[CONTROLLER]
public function showpost()
{
$data = array();
$this->load->view('header',$data);
$data['post'] = $query->result();
$data['similar'] = $this->crudModel->getSimilarPost();
$this->load->view('showfull',$data);
$this->load->view('footer');
}
[MODEL]
public function getSimilarPost()
{
$query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
foreach($query->result() as $row){ $tags = $row->tags; }
$match = explode(',', $tags);
for($i = 0; $i < count($match); $i++)
{
$this->db->like('tags',$match[$i]);
$this->db->from('blogs');
$sqlQuery = $this->db->get();
}
return $sqlQuery->result();
}
[VIEW]
foreach($similar as $row)
{
echo($row->btitle.'<br/>');
}
Try this.
public function showpost()
{
$data = array();
$this->load->view('header',$data);
$data['post'] = $query->result(); // why this line??
$data['similar'] = $this->crudModel->getSimilarPost();
$this->load->view('showfull',$data);
$this->load->view('footer');
}
[MODEL]
public function getSimilarPost()
{
$query = $this->db->get_where('blogs',array('id' => $this->uri->segment(3)));
foreach($query->result() as $row){ $tags = $row->tags }
$match = explode(',', $tags);
$result = [];
for($i = 0; $i < count($match); $i++)
{
$this->db->like('tags',$match[$i]);
$this->db->from('blogs');
$sqlQuery = $this->db->get();
if($sqlQuery->num_rows()>0)
$result[] = $sqlQuery->result();
}
return $result;
}
[VIEW]
$check = [];
foreach($similar as $row)
{
foreach($row as $data)
{
if(!in_array($data->btitle,$check))
{
$check[] = $data->btitle;
echo $data->btitle.'<br/>';
}
}
}
Controller[In Article Page Article Properly work with pagination, store user email id in 'articles' database , now i tried to get the user firstname, and lastname from users table but not work properly ]
public function articles()
{
$data['title'] = "Articles";
$config = array();
$config["base_url"] = base_url() . "sd/articles/";
$config["total_rows"] = $this->model_users->record_count_articles();
$config["per_page"] = 10;
$config["uri_segment"] = 3;
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model_users->fetch_result_articles($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$this->load->view('sd/header',$data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/footer', $data);
} else {
$this->load->view('sd/sdheader', $data);
$this->load->view('sd/articles', $data);
$this->load->view('sd/sdfooter', $data);
}
}
Model [ Get Users Name in Article Page ]
public function record_count_articles() {
return $this->db->where('status','1')->count_all("articles");
}
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->where('status','1')->order_by('id', 'DESC')->get("articles");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Add These Lines [ But Not Work]
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
$query = $this->db->select('firstname')->select('lastname')->where('email',$data[0]->email)->get("users");
$data['name_info']=$query->result_array();
}
return $data;
}
return false;
You have 2 problem here. please have a look on comments in code.
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
//1) $data[0]->email keep repeating same email.
// inner $query variable should be different.
$innerQuery = $this->db->select('firstname,lastname')->where('email',$row->email)->get("users");
//2) you need to store query result on array.
// $data['name_info'] stores only single record.
$data[]=$innerQuery ->result_array();
}
return $data;
}
return false;
You should avoid query in loop if you can achieve it by join
EDIT: Lets try this with join
public function fetch_result_articles($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db
->join('users u','u.email = a.email','left')
->where('a.status','1')->order_by('a.id', 'DESC')->get("articles a");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
I have not tested the code. but it is better way than loop.
Hello guys i am trying to create a blog. The first home page is ok.. i am getting the shrot description and the categories from the database but...i have problems with the links:
this are my controller functions:
public function index()
{
$this->load->model('Model_cats');
$data['posts'] = $this->Model_cats->getLivePosts(10);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = 'Welcome to Paul Harbuz Blog Spot!';
$data['main'] = 'public_home';
$this->load->vars($data);
$this->load->view('template', $data);
}
public function category($id)
{
$data['category'] = $this->Model_cats->getCategory($id);
$data['posts'] = $this->Model_cats->getAllPostsByCategory($id);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = $data['category']['name'];
$data['main'] = 'public_home';
$this->load->vars($data);
$this->load->view('template', $data);
}
public function post($id)
{
$data['post'] = $this->Model_cats->getPost($id);
$data['comments'] = $this->Model_cats->getComments($id);
$data['cats'] = $this->Model_cats->getTopCategories();
$data['title'] = $data['post']['title'];
$data['main'] = 'public_post';
$this->load->vars($data);
$this->load->view('template');
}
this are my model function:
function getTopCategories()
{
$this->db->where('parentid',0);
$query = $this->db->get('categories');
$data = array();
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$data[$row['id']] = $row['name'];
}
}
$query->free_result();
return $data;
}
function getLivePosts($limit)
{
$data = array();
$this->db->limit($limit);
$this->db->where('status', 'published');
$this->db->order_by('pubdate', 'desc');
$query = $this->db->get('posts');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row)
{
$data[] = $row;
}
}
$query->free_result();
return $data;
}
function getCategory($id)
{
$data = array();
$this->db->where('id',$id);
$this->db->limit(1);
$query = $this->db->get('categories');
if($query->num_rows() > 0)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
function getAllPostsByCategory($catid)
{
$data = array();
$this->db->where('category_id', $catid);
$this->db->where('status', 'published');
$query = $this->db->get('posts');
if($query->num_rows() > 0)
{
foreach($query->result_array() as $row){
$data[] = $row;
}
}
$query->free_result();
return $data;
}
function getPost($id)
{
$data = array();
$this->db->where('id',$id);
$this->db->limit(1);
$query = $this->db->get('posts');
if ($query->num_rows() > 0)
{
$data = $query->row_array();
}
$query->free_result();
return $data;
}
and in the view page i have something like this:
if ( count($posts) )
{
foreach ($posts as $key => $list)
{
echo '<h2>'.$list['title'].'</h2>';
echo auto_typography(word_limiter($list['body'], 200));
echo anchor('post/'.$list['id'],'read more >>');
}
echo '<br/><br/>';
}
I'm getting the post id in the url but.. i don't know why the page is not found.
You have to add the controller name to the anchor uri segments.
echo anchor('CONTROLLER/post/'.$list['id'],'read more >>');
More on this topic in the CodeIgniter URLs documentation.
If you want a URL like http://example.com/post/123 then you have to add the following to your application/config/routes.php file:
$route['post/(:num)'] = "CONTROLLER/post/$1";
More on routing is also available in the documentation.
I have the following model functions with PHP.
I know I am repeating myself.
Is there anyway I can simplify this code?
function getTopMenus(){
$data[0] = 'root';
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
function getheadMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
function getrootMenus(){
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
I can see one simplification you might try, using pass-by-reference to factor things out into a function:
function prepareMenu(&$data) {
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['id']] = $row['name'];
}
}
$Q->free_result();
}
function getTopMenus() {
$data[0] = 'root';
prepareMenus($data);
return $data;
}
function getRootMenus() {
prepareMenus($data);
return $data;
}
There's also the possibility of using pass-by-reference and variable functions to factor out the part in the middle. May reduce duplication, but may or may not be considered 'simplifying'.
EDIT Here's what I mean. This code is untested.
function getMenus(&$data, $appendFunc) {
$this->db->where('parentid',0);
$Q = $this->db->get('menus');
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$appendFunc(&$data, $row);
}
}
$Q->free_result();
}
function appendTopMenu(&$data, $row) {
$data[$row['id']] = $row['name'];
}
function appendHeadMenu(&$data, $row) {
$data[] = $row;
}
function getTopMenus() {
$data[0] = 'root';
getMenus($data, "appendTopMenu");
return $data;
}
function getheadMenus() {
getMenus($data, "appendHeadMenu");
return $data;
}
function getrootMenus() {
getMenus($data, "appendTopMenu");
return $data;
}
Why not pass parameters into your function and place them in the 'where' and 'get' methods?
I don't know what your db and query classes look like, but i'd start improving these in the first place. Add "array fetch" and "hash fetch" functions to the query class:
class Query ...
function as_array() {
$data = array();
if($this->num_rows() > 0)
foreach ($this->result_array() as $row)
$data[] = $row;
$this->free_result();
return $data;
}
function as_hash($key = 'id') {
$data = array();
if($this->num_rows() > 0)
foreach ($this->result_array() as $row)
$data[$row[$key]] = $row;
$this->free_result();
return $data;
}
Make 'db->where()' return itself
class DB
function where(...) {
stuff
return $this;
Once you have this, your client functions become trivial:
function getTopMenus() {
$data = $this->db->where('parentid',0)->get('menus')->as_hash();
$data[0] = 'root';
return $data;
}
function getheadMenus() {
return $this->db->where('parentid',0)->get('menus')->as_array();
}
function getrootMenus() {
return $this->db->where('parentid',0)->get('menus')->as_hash();
}