DB query returns only first matching result - php

// Get all categories
$query = "SELECT name FROM bolt_taxonomy WHERE taxonomytype = :taxonomytype AND contenttype = :contenttype";
$map = array(
':taxonomytype' => 'categories',
':contenttype' => 'news',
);
$categories = $this->app['db']->fetchAssoc($query, $map);
$response = $this->app->json(array('categories' => $categories));
return $response;
Returns:
{
"categories": {
"name": "life"
}
}
Which is just the first entry that matches the above condition on the bolt_taxonomy table. How can I get it to return the whole list of categories?

This is now solved by using fetchAll:
// Get the category
$query = "SELECT name FROM bolt_taxonomy WHERE taxonomytype = 'categories' AND contenttype = 'news'";
$categories = $this->app['db']->query($query);
$result = $categories->fetchAll();
$response = $this->app->json(array('categories' => $result));
return $response;

You need to populate using while or foreach loop.
$categories = $this->app['db']->fetchAssoc($query, $map);
foreach($categories as $category) {
$result[] = $category;
}
$response = $this->app->json($result);
echo $response;
return $response;

Related

make foreach into json array

I'm a little confused, and I need help.
I have a foreach loop in my code below. I need to put the foreach loop into the $data = array('image' => $final_image);
How can i put foreach loop in array ? Anyone can help me please.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
// Create an array to store final images
$final_images = [];
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
// Save the image if its new data.
$final_images[]= $final_image;
}
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_images, // We pass the final images array
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}
Made things a bit more verbose.
First define the array.
Then in the if statement add element to the array.
$getImages = isset($GetNewMessageU['imageid']) ? $GetNewMessageU['imageid'] : NULL;
$ExploreImage = explode(",", $getImages);
$CountExplodes=count($ExploreImage);
$final_images = array(); // Define object as array
foreach($ExploreImage as $a) {
$newdata=$Post->Post_GetUploadChatImageID($a);
if($newdata){
$final_image=$base_url."uploads/images/".$newdata['uploaded_image'];
$final_images[] = array('image' => $final_image); // Will create new array item
}
echo $final_image;
}
if($GetNewMessageU){
$json = array();
$data = array(
'image' => $final_image,
);
$result = json_encode( $data );
echo preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $result);
}

Codeigniter SELECT from TABLE problems

I have this code, in my Model:
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => $this->db->query($query)->result_array(),
);
return json_encode($result);
}
}
And this code will return me an array (json type) like:
{"assignedTags":[],"availableTags2":[{"tag":"php"},{"tag":"mysql"}]}
What to change in my code to get an array like:
{"assignedTags":[],"availableTags2":[{"php"},{"mysql"}]}
I just need the values from the key, not with the key.
I don't think this is a feasible or not but you can use array_column as
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => $this->db->query($query)->result_array(),
);
$result['availableTags2'] = array_column($result['availableTags2'],'tag');
return json_encode($result);
}
}
You will need a foreach to do so. There is no automatic way.
$tmp = $this->db->query($query)->result_array();
foreach($tmp as $cell=> $row) {
$tmp_result[] = $row;
}
$result = array(
'assignedTags' => array(),
'availableTags2' => $tmp_result,
);
return json_encode($result);
Use array_values(). This will do:
public function get_all_distinct() {
$query = 'SELECT DISTINCT(tag) FROM `tags_to_questions`';
$result = array(
'assignedTags' => array(),
'availableTags2' => array_values($this->db->query($query)->result_array()),
);
return json_encode($result);
}
}

Sort topics by name

I have the following function to work with:
function listBrandTopics($params){
self::_getParam($params,'article_path',Wrapper::basePath().'article/');
$articles = Array();
$first_pass = true;
$count = 0;
while($result['_links']['next'] || $first_pass){
$count++;
$first_pass = false;
$result = $this->_apiCall(
Array(
'path' => '/brands/'.$params['bid'].'/articles',
'request_param' => Array(
'per_page' => '100',
'page' => $count
)
)
)->getBody();
$result = json_decode($result, true);
$articles = array_merge($articles, array_filter($result['_embedded']['entries'], array($this, '_inSupport')));
}
array_walk($articles, Array($this, '_articlesProcessor'));
$topics = $this->_topicId();
$info = Array();
foreach($articles as $article){
$topic_id = intval($article['topic_id']);
foreach($topics as $topic){
$topic_name = trim($topic['name']);
if($topic_id == $topic['id']){
$info[$topic_name]['id'] = $topic['id'];
if(!is_array($info[$topic_name]['articles'])){
$info[$topic_name]['articles'] = Array();
}
array_push($info[$topic_name]['articles'], $article);
break;
}
}
}
$params['current_brand'] = self::$brand_table[$params['bid']];
$params['the_data'] = $info;
$params['the_data_json'] = json_encode($info);
return $this->_getHtmlTemplate(self::_getParam($params,'template','brandTopics.phtml'),$params);
}
It renders a list of topics and their related articles in a support site.
However, this list of topics is not alphabetically ordered.
I know that $topic['name'] is the name of the topic, but how do I get it to return them in alphabetical order?
Thanks for the help!
Use the function ksort to order $info by key
After:
$info = Array();
foreach($articles as $article){
...
}
Add:
ksort($info);
Use simple sort($array) for alphabetically sorted array.
$this->cars = array("bmw", "audi", "opel", "ford");
sort($this->cars);
Use asort($array) (with sort_flags) if You need to keep key/value association in order.
sort - manual
asort - manual

Using foreach in codeigniter view to generate select options

I ma using codeigniter to generate some html options,but i only get one result,first result from the table.
This is my controller
public function edit_event($id = 0){
$id = $this->uri->segment(3);
$current_id = $this->ion_auth->get_user_id();
$data['data'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
}
This is my model
public function the_groups_list($current_id){
$query = $this->db->get_where('all_groups', array('group_owner' => $current_id));
foreach ($query->result() as $row)
{
$data = array(
'group_title' => $row->group_title,
'group_name' => $row->group_name,
'group_owner' => $row->group_owner
);
return $data;
}
}
This is the other model
public function as_event_edit($id){
$query = $this->db->get_where('all_scheduled_messages', array('id' => $id));
foreach ($query->result() as $row)
{
$data = array(
'as_title' => $row->as_title,
'as_event_name' => $row->as_event_name,
'as_owner' => $row->as_owner,
'as_type' => $row->as_type,
'as_target_dataset' => $row->as_target_dataset,
'as_timestamp' => $row->as_timestamp,
'as_time' => $row->as_time,
'as_day' => $row->as_day
);
return $data;
}
}
I am then using $groups['group_title'] in view and only the first group title gets displayed even though i have like 4 group titles from the other rows.
How can i return and pass an array that i can then to the view so as to use foreach to iterate and display the group titles?.
In your model you're not creating a multi-dimensional array. You need to add keys either using a counter:
$data = array();
$i=0;
foreach ($query->result() as $row){
$data[$i]['as_title'] = $row->as_title;
$data[$i]['as_event_name'] = $row->as_event_name;
$data[$i]['as_owner'] = $row->as_owner;
$data[$i]['as_type'] = $row->as_type;
$data[$i]['as_target_dataset'] = $row->as_target_dataset;
$data[$i]['as_timestamp'] = $row->as_timestamp;
$data[$i]['as_time'] = $row->as_time;
$data[$i]['as_day'] = $row->as_day;
$i++;
);
return $data;
or use the key of the incoming array
$data = array();
foreach ($query->result() as $id => $row){
$data[$id]['as_title'] = $row->as_title;
$data[$id]['as_event_name'] = $row->as_event_name;
$data[$id]['as_owner'] = $row->as_owner;
$data[$id]['as_type'] = $row->as_type;
$data[$id]['as_target_dataset'] = $row->as_target_dataset;
$data[$id]['as_timestamp'] = $row->as_timestamp;
$data[$id]['as_time'] = $row->as_time;
$data[$id]['as_day'] = $row->as_day;
);
return $data;
Change the model from $data = to $data[] = to insert each row and not only one.
In your view loop over the groups, like so:
foreach ($data as $group) {
echo "Title" . $groups['group_title'];
}
RTM: Adding Dynamic Data to the View
In the controller: rename your $data['data'] to $data['event']
$data['event'] = $this->as->the_event_edit($id);
$data['groups'] = $this->as->the_groups_list($current_id);
$this->load->view('editevent',$data);
In your view:
foreach ($event as $items) {
var_dump($items);
}
foreach ($groups as $group) {
var_dump($group);
}

How to access array computer by a function within Codeigniter?

I have a function as follow:
function get_employee_information()
{
$this->db
->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
}
I'm trying to access this data from within an output to template, like this:
$this->get_employee_information();
$output = $this->template->write_view('main', 'records', array(
'employee_names' => $employee_names,
'employee_ids' => $employee_ids,
), false);
Yet this isn't displaying anything. I feel like this is something small and I should know better. When I tun print_r($arrayname) on either array WITHIN the function, I get the suspected array values. When I print_r OUTSIDE of the function, it returns nothing.
Your function is not returning anything. Add the return shown below.
function get_employee_information()
{
$this->db->select('id, name');
$query = $this->db->get('sales_people');
$employee_names = array();
$employee_ids = array();
foreach ($query->result() as $row) {
$employee_names[$row->id] = $row->name;
$employee_ids[] = $row->id;
}
return array(
'employee_names'=>$employee_names,
'employee_ids'=>$employee_ids,
);
}
You are not setting the return value of the function to a variable
$employee_info = $this->get_employee_information();
$output =
$this->template->write_view(
'main', 'records',
array(
'employee_names' => $employee_info['employee_names'],
'employee_ids' => $employee_info['employee_ids'],
),
false
);

Categories