Laravel how get array and not object of QueryBuilder select() statement? - arrays

I have write that code but i want take an array of this, is this possible?
$results = DB::table('pages')->select('id', 'link')->orderBy('id', 'asc')->get();

To get laravel query builder result in array check this:
$results = DB::table('pages')->select('id', 'link')->orderBy('id', 'asc')->get()->toArray();
Or
If you prefer to use Query Builder instead of Eloquent here is the solutions
$results = DB::table('pages')->select('id', 'link')->orderBy('id', 'asc')->get();
First Solution
$array = (array) $result;
Second Solution
$array = get_object_vars($result);
Third Solution
$array = json_decode(json_encode($result), true);
hope it may help

You can see from the API docs that the get() function returns either a Collection or a Builder.
Laravel collections have the toArray() method (described in the docs) as shown below:
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
/*
[
['name' => 'Desk', 'price' => 200],
]
*/
Therefore, you can do the following:
$results = DB::table('pages')->select('id', 'link')->orderBy('id', 'asc')->get()->toArray();

Related

Sorting array in drupal 7

I am a newbie in Drupal. Please accept my ignorance. I have a page with a custom hook to override the view and display list of posts with default sorting or no sorting. I want to sort the array based on the node create date. But not sure where to plug the sorting argument. Can anyone please help? I have this code block in my_view.module file.
function _sites_by_park_page_get_node_references($fieldName, $property, $park_id) {
$results = array();
$parks = _sites_by_park_page_get_sites($park_id);
foreach ($parks['features'] as $feature) {
foreach($feature['properties'][$property] as $key => $value) {
if (!array_key_exists($key, $results)) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->fieldCondition($fieldName, 'value', $value);
$result = $query->execute();
$node = node_load(array_shift(array_keys($result['node'])));
$results[$key] = $node->title;
}
}
}
return $results;
}
/**
* Return GeoJSON formatted park data
*/
function _sites_by_park_page_get_sites($park_id) {
// Uses a lot of memory thanks to views and GD image resizing, could use some garbage collection opimisation
ini_set('memory_limit', '512M');
$data_view = views_get_view('sites_by_park_data');
$data_view->set_arguments(array($park_id));
$data_view->execute('page');
// Build our own, more lightweight geojson structure for faster page loads (Leaflet module generated 2MB of data vs this custom module's 40kb-ish for 140 parks)
$results = array(
'type' => 'FeatureCollection',
'features' => array(),
);
foreach($data_view->result as $result) {
// Initialise some arrays that may be merged between result sets (for instance when multiple activities contribute to a site's overall data)
if (!isset($results['features'][$result->nid])) {
$results['features'][$result->nid] = array(
'type' => 'Feature',
'properties' => array()
);
}
}
$results['features'] = array_values($results['features']);
return $results;
}
As per MilanG's suggestion I have done this through admin section. Change the sorting order and it works fine now.

Drupal: Retrieving database

I'm fairly new to Drupal, and I need your help on this issue:
I have built a module on Drupal 7 which makes a database query to extract the name and the email of all users. The code is this:
<?php
/**
*
*/
function myexample_block_info() {
$blocks['myblock'] = array(
'info' => t('My Custom Modue'),
);
return $blocks;
}
function myexample_block_view($delta = '') {
$block = array();
$results = db_select('users','a')
->fields('a', array('name', 'mail'))
->execute();
$header = array(t('NAME'), t('MAIL'));
$rows = array();
foreach ($results as $node) {
$rows[] = array(
$node->name,
$node->mail,
);
}
$block['content'] = theme('table', array('header' => $header, 'rows' => $rows));
return $block;
}
I put the block into "Side-bar first"-Bartik theme. The code works and it retrieves what I want. But the problem with the display. I'm getting the results repeated 3 times:
Results
Why am I getting the results repeated three times. I cant seem to find anything wrong with the code. Could anyone help me please? Thanks in advance.
What are you trying to achieve ? If you are just trying to extract data from the DB this is not the way to go. You should extract data via mysql client directly.

Return doctrine object to array/json by findall() -gives an error - of on object

I am getting an error on line 10 :
Call to a member function getUserId() on a non-object in
/** #var $users User*/
$users= $this->getRepository("repo")->findAll();
$response = array();
foreach ($users $user) {
$response[] = array(
**line10 'user_id' => $user->getUserId()
);
}
basicly in line 10 it did not recognize the call to getUserId
so how could I fetch the data to array or json ?
thanks
Inside your loop on $campaigns, one of the elements of the array seem to be null, so this element does not have the method getUserId. Try to var_dump your $campaigns array to check its content, I'm pretty sure you would be able to find the mistake after that.
Try: $campaigns = $this->getDoctrine->getRepository("repo")->findAll();
Looks like $campaigns have no results, try:
if($capaigns) {
foreach ($campaigns as $user) {
$response[] = array('user_id' => $user->getUserId());
}
}

Limiting returned wordpress fields from WP_Query or 'get' functions

Looking to limit the returned fields of a WP Query to help with speeding up the response from the server and reducing the amount of data retrieved. For the query I'm using, it only needs up to 3 fields of data, the rest is brought in through ACF get_field_object in the loop. Other functions I'm using such as get_posts or get_terms have field options but are limited to a small number of things, such as 'slug' only or 'id => slug'.
I'm used to developing in CakePHP, which has the option to specify each and every field to return, but the project calls for wordpress for other functionality and so I'm quite limited.
TL;DR need to speed up getting posts from Wordpress
I used fields parameter in the query and run get posts on this query.
For example: In my case, I just needed to get the Post ids for multiple categories, so I created a query like this:
$the_query = new WP_Query( array(
'ignore_sticky_posts' => 1,
'posts_per_page' => -1,
'cat' => '2,6,7' ,
'fields' => 'ids',
'post_type' => 'post',
'post_status' => 'publish',
)
);
Run the get_posts on this query:
$posts = $the_query->get_posts();
$posts will get only the IDs of particular categories posts.
Or it can also be done with the standard and popular way and i.e., by running the loop of have_posts:
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$post_id_array[] = get_the_ID();
}
}
These are the two ways to help with speeding up the response from the server and reducing the amount of data retrieved
WP_Query will return objects...so it's pretty fast. However, if you really want to limit what's returned, you can do so with the Return Fields Parameter of WP_Query.
I don't know how much it will help but below is how I'm getting a flattened array from a CPT. It's not the fastest but it could be worse. I'm using ACF to get a Custom Field but you could just get back the slug or you could get back multiple fields instead:
// Query Jobs Args
$query_args = array(
'post_type' => 'job',
'posts_per_page' => -1,
'fields' => 'ids'
);
// Get Jobs Query
$query = new WP_Query($query_args);
// Loop Persistent Vars
$job_ids = array();
// Loop Over Jobs
foreach($query->posts as $post_id) {
$job_ids[] = get_field('job_id', $post_id);
}
// Do stuff with flattened array of job ids
This is what I've done to limit the fields from WP_Query, especially, when I want to json_encode them. The $return variable contains my array of posts with only the fields listed in the $fields array.
$query = new WP_Query( array( 'post_type' => 'my_custom_type' ) );
$return = array();
$fields = array('post_title', 'ID'); //list of fields I want in $return
$posts = $query->get_posts();
foreach($posts as $post) {
$newPost = array();
foreach($fields as $field) {
$newPost[$field] = $post->$field;
}
$return[] = $newPost;
}
Interestingly enough, you can do this with the WP Rest API using the _fields parameter
https://yoursite.com/wp-json/wp/v2/posts?_fields=author,id,excerpt,title,link
More info on the API here: https://developer.wordpress.org/rest-api/

CodeIgniter - return only one row?

At the moment if I am doing a query on the database that should only return one row, using:
...query stuff...
$query = $this->db->get();
$ret = $query->result();
return $ret[0]->campaign_id;
Is there a CodeIgniter function to return the first row?
something like $query->row();
Or even better would be the ability to, if there was only one row,
to just use the query object directly.
e.g. $query->campaign_id;
You've just answered your own question :)
You can do something like this:
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
You can read more about it here: http://www.codeigniter.com/user_guide/database/results.html
This is better way as it gives you result in a single line:
$this->db->query("Your query")->row()->campaign_id;
To add on to what Alisson said you could check to see if a row is returned.
// Query stuff ...
$query = $this->db->get();
if ($query->num_rows() > 0)
{
$row = $query->row();
return $row->campaign_id;
}
return null; // or whatever value you want to return for no rows found
To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:
if ($query->num_rows() > 0) {
return $query->first_row();
}
To retrieve the first row.
$this->db->get()->row()->campaign_id;
Change only in two line and you are getting actually what you want.
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
try it.
If you require to get only one record from database table using codeigniter query then you can do it using row(). we can easily return one row from database in codeigniter.
$data = $this->db->get("items")->row();
We can get a single using limit in query
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);
You can do like this
$q = $this->db->get()->row();
return $q->campaign_id;
Documentation :
http://www.codeigniter.com/user_guide/database/results.html
Option 1
$limit = 1
$offset = 0
$query = $this->db->get_where('items', array('id' => $id), $limit, $offset);
Option 2
$this->db->get("items")->row();
class receipt_model extends CI_Model {
public function index(){
$this->db->select('*');
$this->db->from('donor_details');
$this->db->order_by('donor_id','desc');
$query=$this->db->get();
$row=$query->row();
return $row;
}
}

Resources