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;
}
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.
I'm running into a Problem that my grid isn't Sorting/Filtering as expected. I always get all results back from the database.
Here is my JS:
<script>
'use strict';
(function($, kendo) {
$("#grid").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url:"http://server01/read.php",
type: "POST"
}
},
schema: {
data: "data",
total: "total",
model: {
fields: {
tID: { type: "number" },
tTitle: { type: "string" },
oDate: { type: "date" },
eDate: { type: "date" },
cDate: { type: "date" },
tKeywords: { type: "string" }
}
}
},
pageSize: 2,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
height: 430,
filterable: true,
sortable: true,
pageable: true,
columns: [{
field:"tID",
title:"TicketID",
width:"60px",
filterable: false
},{
field: "tTitle",
title: "Ticket Bezeichnung"
}, {
field: "oDate",
title: "Ticket eröffnet",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "eDate",
title: "Ticket escaliert",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "cDate",
title: "Ticket geschlossen",
format: "{0:MM/dd/yyyy}",
width: "160px"
}, {
field: "tKeywords",
title: "keywords"
}
]
});
})(jQuery, kendo);
On the Server side it looks like this:
error_reporting(E_ALL);
include 'classes/classes.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Content-Type: application/json');
$request = json_encode($_POST);
$result = new DataSourceResult('mysql:host=localhost;dbname=jarvis','root','',array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
echo json_encode($result->read('jar_ticketing_index', array('tID', 'tTitle', 'tDesc', 'oDate', 'eDate', 'cDate','tKeywords'), $request));
}else{
echo "Opps...";
}
For applying the filters to the Query I'm using the dataSourceResult class:
class DataSourceResult {
private $db;
private $stringOperators = array(
'eq' => 'LIKE',
'neq' => 'NOT LIKE',
'doesnotcontain' => 'NOT LIKE',
'contains' => 'LIKE',
'startswith' => 'LIKE',
'endswith' => 'LIKE'
);
private $operators = array(
'eq' => '=',
'gt' => '>',
'gte' => '>=',
'lt' => '<',
'lte' => '<=',
'neq' => '!='
);
private $aggregateFunctions = array(
'average' => 'AVG',
'min' => 'MIN',
'max' => 'MAX',
'count' => 'COUNT',
'sum' => 'SUM'
);
function __construct($dsn, $username=null, $password=null, $driver_options=null) {
$this->db = new PDO($dsn, $username, $password, $driver_options);
}
private function total($tableName, $properties, $request) {
if (isset($request->filter)) {
$where = $this->filter($properties, $request->filter);
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName $where");
$this->bindFilterValues($statement, $request->filter);
} else {
$statement = $this->db->prepare("SELECT COUNT(*) FROM $tableName");
}
$statement->execute();
$total = $statement->fetch(PDO::FETCH_NUM);
return (int)($total[0]);
}
private function page() {
return ' LIMIT :skip,:take';
}
private function group($data, $groups, $table, $request, $properties) {
if (count($data) > 0) {
return $this->groupBy($data, $groups, $table, $request, $properties);
}
return array();
}
private function mergeSortDescriptors($request) {
$sort = isset($request->sort) && count($request->sort) ? $request->sort : array();
$groups = isset($request->group) && count($request->group) ? $request->group : array();
return array_merge($sort, $groups);
}
private function groupBy($data, $groups, $table, $request, $properties) {
if (count($groups) > 0) {
$field = $groups[0]->field;
$count = count($data);
$result = array();
$value = $data[0][$field];
$aggregates = isset($groups[0]->aggregates) ? $groups[0]->aggregates : array();
$hasSubgroups = count($groups) > 1;
$groupItem = $this->createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties);
for ($index = 0; $index < $count; $index++) {
$item = $data[$index];
if ($item[$field] != $value) {
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
$groupItem = $this->createGroup($field, $data[$index][$field], $hasSubgroups, $aggregates, $table, $request, $properties);
$value = $item[$field];
}
$groupItem["items"][] = $item;
}
if (count($groups) > 1) {
$groupItem["items"] = $this->groupBy($groupItem["items"], array_slice($groups, 1), $table, $request, $properties);
}
$result[] = $groupItem;
return $result;
}
return array();
}
private function addFilterToRequest($field, $value, $request) {
$filter = (object)array(
'logic' => 'and',
'filters' => array(
(object)array(
'field' => $field,
'operator' => 'eq',
'value' => $value
))
);
if (isset($request->filter)) {
$filter->filters[] = $request->filter;
}
return (object) array('filter' => $filter);
}
private function addFieldToProperties($field, $properties) {
if (!in_array($field, $properties)) {
$properties[] = $field;
}
return $properties;
}
private function createGroup($field, $value, $hasSubgroups, $aggregates, $table, $request, $properties) {
if (count($aggregates) > 0) {
$request = $this->addFilterToRequest($field, $value, $request);
$properties = $this->addFieldToProperties($field, $properties);
}
$groupItem = array(
'field' => $field,
'aggregates' => $this->calculateAggregates($table, $aggregates, $request, $properties),
'hasSubgroups' => $hasSubgroups,
'value' => $value,
'items' => array()
);
return $groupItem;
}
private function calculateAggregates($table, $aggregates, $request, $properties) {
$count = count($aggregates);
if (count($aggregates) > 0) {
$functions = array();
for ($index = 0; $index < $count; $index++) {
$aggregate = $aggregates[$index];
$name = $this->aggregateFunctions[$aggregate->aggregate];
$functions[] = $name.'('.$aggregate->field.') as '.$aggregate->field.'_'.$aggregate->aggregate;
}
$sql = sprintf('SELECT %s FROM %s', implode(', ', $functions), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
return $this->convertAggregateResult($result[0]);
}
return (object)array();
}
private function convertAggregateResult($properties) {
$result = array();
foreach($properties as $property => $value) {
$item = array();
$split = explode('_', $property);
$field = $split[0];
$function = $split[1];
if (array_key_exists($field, $result)) {
$result[$field][$function] = $value;
} else {
$result[$field] = array($function => $value);
}
}
return $result;
}
private function sort($properties, $sort) {
$count = count($sort);
$sql = '';
if ($count > 0) {
$sql = ' ORDER BY ';
$order = array();
for ($index = 0; $index < $count; $index ++) {
$field = $sort[$index]->field;
if (in_array($field, $properties)) {
$dir = 'ASC';
if ($sort[$index]->dir == 'desc') {
$dir = 'DESC';
}
$order[] = "$field $dir";
}
}
$sql .= implode(',', $order);
}
return $sql;
}
private function where($properties, $filter, $all) {
if (isset($filter->filters)) {
$logic = ' AND ';
if ($filter->logic == 'or') {
$logic = ' OR ';
}
$filters = $filter->filters;
$where = array();
for ($index = 0; $index < count($filters); $index++) {
$where[] = $this->where($properties, $filters[$index], $all);
}
$where = implode($logic, $where);
return "($where)";
}
$field = $filter->field;
if (in_array($field, $properties)) {
$index = array_search($filter, $all);
$value = ":filter$index";
if ($this->isDate($filter->value)) {
$field = "date($field)";
$value = "date($value)";
}
if ($this->isString($filter->value)) {
$operator = $this->stringOperators[$filter->operator];
} else {
$operator = $this->operators[$filter->operator];
}
return "$field $operator $value";
}
}
private function flatten(&$all, $filter) {
if (isset($filter->filters)) {
$filters = $filter->filters;
for ($index = 0; $index < count($filters); $index++) {
$this->flatten($all, $filters[$index]);
}
} else {
$all[] = $filter;
}
}
private function filter($properties, $filter) {
$all = array();
$this->flatten($all, $filter);
$where = $this->where($properties, $filter, $all);
return " WHERE $where";
}
private function isDate($value) {
$result = date_parse($value);
return $result["error_count"] < 1;
}
private function isString($value) {
return !is_bool($value) && !is_numeric($value) && !$this->isDate($value);
}
private function bindFilterValues($statement, $filter) {
$filters = array();
$this->flatten($filters, $filter);
for ($index = 0; $index < count($filters); $index++) {
$value = $filters[$index]->value;
$operator = $filters[$index]->operator;
$date = date_parse($value);
if ($operator == 'contains' || $operator == 'doesnotcontain') {
$value = "%$value%";
} else if ($operator == 'startswith') {
$value = "$value%";
} else if ($operator == 'endswith') {
$value = "%$value";
}
$statement->bindValue(":filter$index", $value);
}
}
public function create($table, $properties, $models, $key) {
$result = array();
$data = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$columns = array();
$values = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$columns[] = $property;
$values[] = '?';
$input_parameters[] = $model->$property;
}
}
$columns = implode(', ', $columns);
$values = implode(', ', $values);
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
} else {
$model->$key = $this->db->lastInsertId();
$data[] = $model;
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
} else {
$result['data'] = $data;
}
return $result;
}
public function destroy($table, $models, $key) {
$result = array();
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$sql = "DELETE FROM $table WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute(array($model->$key));
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
return $result;
}
public function update($table, $properties, $models, $key) {
$result = array();
if (in_array($key, $properties)) {
if (!is_array($models)) {
$models = array($models);
}
$errors = array();
foreach ($models as $model) {
$set = array();
$input_parameters = array();
foreach ($properties as $property) {
if ($property != $key) {
$set[] = "$property=?";
$input_parameters[] = $model->$property;
}
}
$input_parameters[] = $model->$key;
$set = implode(', ', $set);
$sql = "UPDATE $table SET $set WHERE $key=?";
$statement = $this->db->prepare($sql);
$statement->execute($input_parameters);
$status = $statement->errorInfo();
if ($status[1] > 0) {
$errors[] = $status[2];
}
}
if (count($errors) > 0) {
$result['errors'] = $errors;
}
}
if (count($result) == 0) {
$result = "";
}
return $result;
}
public function read($table, $properties, $request = null) {
$result = array();
$result['total'] = $this->total($table, $properties, $request);
$sql = sprintf('SELECT %s FROM %s', implode(', ', $properties), $table);
if (isset($request->filter)) {
$sql .= $this->filter($properties, $request->filter);
}
$sort = $this->mergeSortDescriptors($request);
if (count($sort) > 0) {
$sql .= $this->sort($properties, $sort);
}
if (isset($request->skip) && isset($request->take)) {
$sql .= $this->page();
}
$statement = $this->db->prepare($sql);
if (isset($request->filter)) {
$this->bindFilterValues($statement, $request->filter);
}
if (isset($request->skip) && isset($request->take)) {
$statement->bindValue(':skip', (int)$request->skip, PDO::PARAM_INT);
$statement->bindValue(':take', (int)$request->take, PDO::PARAM_INT);
}
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
if (isset($request->group) && count($request->group) > 0) {
$data = $this->group($data, $request->group, $table, $request, $properties);
$result['groups'] = $data;
} else {
$result['data'] = $data;
}
if (isset($request->aggregate)) {
$result["aggregates"] = $this->calculateAggregates($table, $request->aggregate, $request, $properties);
}
return $result;
}
}
I always get all of the records back from the database. It looks like my DataSourceResult Object isn't getting the filter variables the right way. But I don't see any error at all.
Could you give me a hint?
Oke I pointed it out. The Filter I got by POST need to be passed as an object to the dataSourceResult Class.
$object = json_decode(json_encode($_POST), FALSE);
Now its working like a charm!
Helo. I’m trying to make a items pagination. I have 3 function, first displaying category, 2nd displaying sucategory. 3rd displaying items is cold get_books_by_subcategory. 3rd function get a segment->url(3) argumnet, i want to make a pagination in the same function. but i cant do it.
This is functions code in controller:
function get_category()
{
$query = $this->Kategorie_model->get_category();
$this->response['podkategorie'] = '';
$this->response['kategorie'] = '';
$podkategorie = '';
if($query->num_rows() > 0)
{
foreach($query->result() as $item)
{
$podkategorie = $this->get_sub_category($item->CAT_ID);
$this->response['kategorie'] .= $this->load->view('Ksiegarnia/left', array('kategorie' =>$item, 'podkategorie'=>$podkategorie), true);
}
}
$data = $this->response['kategorie'];
return $data;
}
function get_sub_category($id)
{
$this->response['wynik'] = '';
$query = $this->Kategorie_model->get_sub_category($id);
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$link = site_url('ksiegarnia/get_books_by_subcategory/'.$row->SUBC_ID);
$this->response['wynik'] .= '<div class="subcat_name">'.$row->SUBC_Name.'</div>';
}
}
else
{
$this->response['wynik'] = '<H1>BRAK DANYCH </H1>';
}
return $this->response['wynik'];
}
function get_books_by_subcategory()
{
$widok['center'] = '';
$widok['left'] = $this->get_category();
$widok['right'] = $this->load->view('Ksiegarnia/right', '', true);
$id = $this->uri->segment(3);
if(isset($id) and is_numeric($id))
{
$query = $this->Kategorie_model->get_books_by_subcategory($id, $this->uri->segment(4));
if($query->num_rows() > 0)
{
foreach($query->result() as $item)
{
$widok['center'] .= $this->load->view('Ksiegarnia/get_books', array('data' =>$item), true);
}
}
else
{
$widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);;
}
$widok['center'] .= $this->pagination->create_links();
$this->load->view('Ksiegarnia/index', $widok);
}
}
And this is my model:
function get_books_by_subcategory($id, $offset=0)
{
$config['base_url'] = 'http://lukaszbielecki.cba.pl/ksiegarnia/CI/index.php/ksiegarnia/get_books_by_subcategory/'.$id;
$config['per_page'] = 7;
$this->db->where('SUB_CATEGORY_SUBC_ID', $id);
$config['total_rows'] = $this->db->get('books')->num_rows();
$config['num_links'] = 20;
$this->pagination->initialize($config);
return $this->db->get('books',$config['per_page'],$offset);
//$wynik = $this->db->query("Select * from books where SUB_CATEGORY_SUBC_ID = '".$id."'");
//return $wynik;
}
The arguments in url is changing, but dispalyin only a items from first subcategory.
Help, please.
On this line $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);; in your controller, you have an additional semicolon ; that is causing a syntax error.