In laravel the get() method over the DB returns an array of stdObjs,
for example this one:
$designers = DB::table('designers')->get();
Will return all designers from the designers table as an array of stdObj.
Now I want to manually create an array of stdObjs using something like this:
public function index()
{
$id = Auth::id();
$user = User::find($id);
foreach ($user->owned_item as $i) {
$result = new \stdClass();
$result->type => $i->Item_type->type,
$result->color => $i->Item_color->color
}
obviously that code will overwrite the $result obj at every cycle, the question is, how do I create an array of all the stdobjs I need?
You need to assign them to an array before the loop execution ends for each item.
$objs = [];
foreach (...) {
$obj = new \stdClass();
...
$objs[] = $obj;
}
After the loop the $objs variable contains an array containing the objects created inside the foreach loop.
EDIT: if you want to set specific array keys for each object, you can use
$objs[$key_here] = $obj;
when inserting the objects to the array. $key_here should be a string or an integer.
Related
In my Symfony project I am returning all objects with Doctrine query builder defined with Paginator.
When dumping $posts['data'], response is on the image: IMAGE
When entering the loop and dumping first result, this is what I get: IMAGE
I want on each array object to assign new key-value pair. Every array object has destinationId (you can see on the image), and I have a method that searches for the name by that param.
I want to assign that new value to every object in foreach.
Code:
$posts = $this->entityManager->getRepository(Post::class)->getPage();
foreach ($posts['data'] as $postsData) {
foreach ($postsData as $post) {
$destinationName = $this->destinationService->getDestinationNameById(
$post->getDestinationId()
);
$postsData['destinationName'] = $destinationName;
}
}
Error is:
Call to a member function getDestinationId() on string
This is very odd as this field has entity type defined as string and also when dumping
dump($post->getDestinationId());
I get: "107869901061558" which is string.
It's because you override you $postsData variable.
You need to use a different variable to store your $destinationName like this :
$posts = $this->entityManager->getRepository(Post::class)->getPage();
$destinationNames = [];
foreach ($posts['data'] as $postsData) {
foreach ($postsData as $post) {
$destinationName = $this->destinationService->getDestinationNameById(
$post->getDestinationId()
);
$destinationNames[$post->getId()] = $destinationName;
}
}
Like this, you could send $destinationNames to your template and find the right $destinationName thanks to the index.
I am passing an array from controller to view in PHP CodeIgniter.
Here is my code in controller.
$gen is any array containing many values.
foreach ($gen as $value) {
$moviesbyid['similarmovie'] = $this->main_model->getsimilarmovies($value);
}
$this->load->view('home/check.php', $moviesbyid);
But the above code fill $moviesbyid['similarmovie'] array only for one value of $value.
I want that it contain all the values returned from getsimilarmovies($value) for every value of $value.
How can i do this?
Here is the method in model:
public function getsimilarmovies($gener)
{
$this->db->limit(4);
$this->db->like('Genre',$gener);
$query = $this->db->get('sources');
return $query->result();
}
You need to create new items in the array as it loops.
Your code just overwrite the same item every iteration.
foreach ($gen as $value) {
$moviesbyid['similarmovie'][]=$this->main_model-
>getsimilarmovies($value);
}
notice the []
I have a function in my model that get all company details I am fetch this
I have to add a new key city_name in my return result() how can I add ?? I am very confused but I am not get any useable example.
function xxxx($search=array(),$page,$limit){
$this->db->select("*");
$this->db->from("xxx");
$this->db->join("xx","xx.xx=xxx.xx");
$this->db->limit($limit,$page);
$company_data = $this->db->get();
if($company_data->num_rows()){
return $company_data->result();
}
else{
return 0;
}
}
Change the following line:
return $company_data->result(); // It return Stc Class Object
to
return $company_data->result_array(); // Now it returns an array
Now you can use array_push() function, it inserts one or more elements to the end of an array.
Or simply use:
$company_data['index'] = value;
Keep your model same return $company_data->result().
In your controller, you need to iterate it for the number of results you get and add new key to your objects.(result() method returns Standard Class Object).
function yourControllerMethod()
{
$company_data = $this->your_model->xxx(search_array, $page, $limit);
if(!empty($company_data)
{
foreach($company_data as $cd)
{
$cd->city_name = "pune"; // or anything you want
}
}
var_dump($company_data);
}
Try this to add new key to your results.
Edit:
You asked that you don't have city_name key in your object.
Yes, you don't have. The above code adds a key in your object.
Just like array.
$temp = array();
$temp["id"] = 1;
In this code, initially the array is empty, the next statement add the id as key in the array.
views.php
$events = array($events); //convert $events objects to array
asort($events); //sort array in ascending order
foreach($events as $event): //iterate array
echo $event; //getting error here
endforeach;
tried this also,
foreach($events as $key => $event): //iterate array
echo "$key = $event\n"; //getting error here
endforeach;
I am trying to iterate the array in foreach loop but i am getting this error "ErrorException [ Recoverable Error ]: Object of class Database_MySQL_Result could not be converted to string"
Need help to solve this.
$events = array($events);
This line does not convert objects to array, but it just inserts object into array;
So $events[0] equals old $events;
I don't know how you pull your data from DB, but as long as it's Kohana, maybe this would work:
$events = $events->as_array();
try casting events as an array, instead of inserting it into array like:
$events = (array)$events;
this will result in all public properties on the $events object being set as an assoc array.
I need to initialize an array of objects in PHP.
Presently I have the following code:
$comment = array();
And when i am adding an element to the array
public function addComment($c){
array_push($this->comment,$c);
}
Here, $c is an object of class Comment.
But when I try to access an functions of that class using $comment, I get the following error:
Fatal error: Call to a member function
getCommentString() on a non-object
Can anyone tell me how to initialize an array of objects in php?
Thanks
Sharmi
$this->comment = array();
Looks like a scope problem to me.
If $comments is a member of a class, calling $comments inside a function of that class will not actually use the member, but rather use an instance of $comments belonging to the scope of the function.
If other words, if you are trying to use a class member, do $this->comments, not just $comments.
class foo
{
private $bar;
function add_to_bar($param)
{
// Adds to a $bar that exists solely inside this
// add_to_bar() function.
$bar[] = $param;
// Adds to a $bar variable that belongs to the
// class, not just the add_to_bar() function.
$this->bar[] = $param;
}
}
This code might help you:
$comments = array();
$comments[] = new ObjectName(); // adds first object to the array
$comments[] = new ObjectName(); // adds second object to the array
// To access the objects you need to use the index of the array
// So you can do this:
echo $comments[0]->getCommentString(); // first object
echo $comments[1]->getCommentString(); // second object
// or loop through them
foreach ($comments as $comment) {
echo $comment->getCommentString();
}
I think your problem is either how you are adding the objects to the array (what is $this->comment referencing to?) or you may be trying to call ->getCommentString() on the array and not on the actual objects in the array.
You can see what's in the array by passing it to print_r():
print_r($comment);
Presuming you have Comment objects in there, you should be able to reference them with $comment[0]->getCommentString().