I wrote an API call in symfony to return all array data from database.
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
array_push($data, $user->getId());
array_push($data, $user->getEmail());
array_push($data, $user->getUsername());
}
return $data;
}
I got it like this
1,first#mail.com,userOne,2,second#gamail.com,userTwo
but I want to sort every group of data in new row like
1,first#mail.com,userOne,
2,second#gamail.com,userTwo
Another way of doing it would be:
public function getData()
{
$users = $this->getUserRepository()->findAll();
foreach ($users as $user) {
$data[] = [$user->getId(), $user->getEmail(),$user->getUsername()];
}
return $data;
}
Which removes the overhead of the function call array_push().
Source: http://php.net/manual/en/function.array-push.php
All of previous answers are not so good in my opinion. You don't need additional loop, just create query. (And return with your needed hydration)
For example
public function test()
{
return $this->createQueryBuilder('user')
->select('user.id, user.email, user.username')
->getQuery()
->getResult(); // will return objects
// ->getArrayResult() -> will return array of arrays
}
Place it in your user repository and then call it, not the findAll method.
this should work
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
$data[$user->getId()][] = $user->getId();
$data[$user->getId()][] = $user->getEmail();
$data[$user->getId()][] = $user->getUsername();
}
return $data;
}
You are creating 3 occurances in $data for each row returned from the database, instead load a single occurance for each returned row and put an array in it.
public function getData()
{
$data = [];
$users = $this->getUserRepository()->findAll();
foreach ($users as $user){
array_push($data, [$user->getId(), $user->getEmail(),$user->getUsername()]);
}
return $data;
}
Thank you all guys for help but I did it like this and it works for me.
public function getData()
{
$results = $this->getUserRepository()->findAll();
$rows = [];
$rows[] = array(
"id",
"username",
"email"
);
foreach ($results as $row) {
$rows[] = array(
$row->getId(),
$row->getUsername(),
$row->getEmail()
);
}
return $rows;
}
$users = $this->getUserRepository()->findAll();
$i=0;
foreach ($users as $user){
$data[$i][] = $user->getId();
$data[$i][] = $user->getEmail();
$data[$i][] = $user->getUsername();
$i++;
}
Related
I am doing the function of creating dynamic menu in laravel and I have the tbl_menu table as below:
menu_id parent_id menu_name link order
1 0 Level_1 url_1 1
2 0 Level_1 url_2 1
3 2 Level_2 url_3 2
4 2 Level_2 url_4 3
5 4 Level_3 url_5 3
I want the result to be an array that looks like this:
-Level_1
-Level_2
-Level_2
-Level_1
_Level_2
_Level_2
_Level_3
My code is as follows:
public function SelectAllChildeLv1ByParentId($id){
$result = DB::table('tbl_menu')->where('parent_id', $id)
->orderBy('order', 'asc')->get();
return $result;
}
public function SelectAllMenuParent(){
$result = DB::table('tbl_menu')->where('parent_id', 0)
->orderBy('order', 'asc')->get();
return $result;
}
public function getMenuChildren($listParent, $step = 3)
{
$results = [];
if ($step > 0) {
$step--;
if($listParent) {
foreach($listParent as $index => $parent) {
$listChild = $this->SelectAllChildeLv1ByParentId($parent->menu_id);
$listChild1 = $this->getMenuChildren($listChild, $step);
$results[$index] = $parent;
$results[$index]->menu_child = $listChild1;
}
}
}
return $results;
}
public function getAllMenus() {
$allMenuParent = $this->SelectAllMenuParent();
$results = $this->getMenuChildren($allMenuParent);
return $results;
}
The results are correct but are running too many queries. I want to optimize it but haven't figured it out yet.
Thanks for any help.
try :
public function get()
{
$menu = DB::table('tbl_menu')
->orderBy('order', 'asc')->get();
$parents = $menu->where('parent', 0);
$items = self::tree($parents, $menu);
return $items;
}
public function tree($items, $all_items)
{
$data_arr = array();
foreach ($items as $i => $item) {
$data_arr[$i] = $item->toArray(); //all column attributes
$find = $all_items->where('parent', $item->id);
//$data_arr[$i]['tree'] = array(); empty array or remove if you dont need it
if ($find->count()) {
$data_arr[$i]['tree'] = self::tree($find, $all_items);
}
}
return $data_arr;
}
Use eloquent.
First, add this to the 'tbl_menu' model:
protected $with = ['children'];
public function children()
{
return $this->hasMany(YOUR_CLASS_NAME::class, 'parent_id', 'id')->orderBy('order');
}
Now if you call the main menu, and all children.
etc: YOUR_CLASS_NAME::where('parent_id', 0)->get().
Then you can use recursion when calling
public $menus = [];
public $level = 0;
public function getMenus($request){
$menus = YOUR_CLASS_NAME::where('parent_id', 0)
->orderBy('order')
->get();
$this->recursiveMenu($menus);
return $this->menus;
}
public function recursiveMenu($menus, $lvl = 0){
foreach ($menus as $key => $menu) {
$this->menus[$menu->id] = str_repeat('—', $lvl).' '.$menu->title;
if($menu->children){
$this->level++;
$this->recursiveMenu($menu->children, $this->level);
}
if (!isset($menu[$key+1])) {
$this->level--;
}
}
}
The model Person has has-many relation to PersonType:
public function getPersonTypes()
{
return $this->hasMany(PersonType::className(), ['PersonID' => 'PersonID']);
}
I need to show in view all PersonType's related values.
Model Person:
public function ListPersonTypes()
{
$data = $this->getPersonTypes()->all();
$list = array();
foreach ($data as $value) {
$list[] = $value['PersonTypeName'];
return implode(', ', $list);
}
}
But, why ListPersonTypes() returns only first row from table PersonType?
public function ListPersonTypes()
{
$data=$this->getPersonTypes;
$list=array();
foreach ($data as $value){
$list[]=$value['PersonTypeName'];
return implode(',',$list);
}
}
Should do the trick.
you don't use it correctly $this->getPersonTypes()->all(); use
this $this->personTypes
write the return out of the loop
Yii2 (gii) by default create this functions for you access that like a attribute of model and return as arrray .
This function hasnt be creates to access as a function literal .
Try this code
public function ListPersonTypes()
{
// this go to function getPersonTypes and return a array of them
$data=$this->personTypes;
$list=array();
foreach ($data as $value){
$list[]=$value['PersonTypeName'];
}
return implode(',',$list);
}
Seems that in your code you are running just one iteration... as you call a return inside the foreach.
public function ListPersonTypes()
{
$data = $this->getPersonTypes()->all();
$list = array();
foreach ($data as $value) {
$list[] = $value['PersonTypeName'];
}
return implode(', ', $list);
}
How to pass the array into another page?
Example is I have the controller code below
$values = array(
'RECEIVER_PHYSICAL',
'RECEIVER_VIRTUAL',
'EMAIL_TEMPLATE'
);
foreach ($values as $id) {
$data['email'] = $this->mod_rewards->getEmail($id);
}
And this is the model that I want to pass the array
public function getEmail($id) {
$info = $this->core_db->select('*')
->from($this->schema.'.'.$this->v_system_config)
->where("key",$id)
->get();
return $return;
}
You can just add a new argument to the method getEmail.
$values = array(
'RECEIVER_PHYSICAL',
'RECEIVER_VIRTUAL',
'EMAIL_TEMPLATE'
);
foreach ($values as $id) {
$data['email'] = $this->mod_rewards->getEmail($id, $values);
}
add the argument like this:
public function getEmail($id, $values) {
though i think there must be something wrong with the design here.
Just rewrite your model function as:
public function getEmail($id,$array) {
//use array here
$info = $this->core_db->select('*')
->from($this->schema.'.'.$this->v_system_config)
->where("key",$id)
->get();
return $return;
}
While calling this model in controller you need to pass this array.
I have a simple array thats returned when executing:
$this->forecast($value->id,$value->db_connection)
when I call the $reports::create($data) it duplicates each row, i have added some logic to print out $data within the foreach and it never returns duplicates, when printing the $result object it has 2 entries.
any idea where i am going wrong?
public function store() // function to store report data in db
{
$reports = new Reports;
$companyData = new ClientSettings;
$settings = $companyData::all();
foreach ($settings as $value) {
$data = $this->forecast($value->id,$value->db_connection);
$result = $reports::create($data);
}
echo "Forecast generated";
}
public function store() // function to store report data in db
{
$reports = new Reports;
$companyData = new ClientSettings;
$settings = $companyData::all();
foreach ($settings as $value) {
$data = $this->forecast($value->id,$value->db_connection);
$result = Reports::create($data);
}
echo "Forecast generated";
}
I'm trying to use OOP ways. I have bunch of methods that return same format of array. I want to guarantee that user of this class knows what will be returned. How would I go about doing that? Please forgive me as I'm not sure of correct terminologies to describe my problem.
class myModel {
public function getArray1(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
public function getArray2(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
public function getArray3(){
$data = array();
$id = array();
....
return array('data'=>$data, 'id'=>$id); <== HOW TO GUARANTEE RETURN FORMAT
};
}
You can try to define additional class for returning value:
class returnArray {
$data = array();
$id = array();
function construct($data,$id) {
$this->data = $data;
$this->id = $id;
}
}
//...
public function getArray1(){
$data = array();
$id = array();
....
return new returnArray('data'=>$data, 'id'=>$id);
};
Then You can add accessors to the returnArray class or leave it as public if You want or even implement __toString() if necessary.