I have wrote PHP function in my Symfony project returnAllPosts() which returns all entity objects from table that are found.
I want to assign new array structure with different keys and put those values of every specific post after that and return new array result with predefined post key-value pairs.
But this specific code returns just first object not all of them? How I can get them all from foreach loop?
$posts = $this->myService->returnAllPosts();
foreach ($posts as $post) {
$post = [
'valueOne' => $post->getValueOne(),
'valueTwo' => $post->getValueTwo(),
];
$posts[] = $post;
}
return $posts;
Related
So I have three different arrays with the same length in the request and below is how I combine them into one collection:
$inputs = collect();
$keys = collect(['id', 'username', 'email']);
foreach ($request['ids'] as $index => $id) {
$username = $request['usernames'][$index];
$email = $request['emails'][$index];
$inputs->push($keys->combine([$id, $username, $email]));
}
The result looks correct to me:
However, I cannot access the collection when I iterate over it:
foreach ($inputs as $input) {
dd($input->id); // Property [id] does not exist on this collection instance.
}
This is the result of dd($input):
Any pointers on this problem? (Another short way to combine the arrays into one collection will also be appreciated!)
Thank you.
It is a collection and you should get it like this: dd($input['id']).
You can combine arrays bt array_merge
array_merge($a1,$a2)
or collect
$c=collect([$arr1,$arr2])
then pluck if you want
$c->pluck('username')
I want to create a multidimensional array to save the data according the date and a category as follow. Then i need to display this data in my blade view?what can i do to achieve this.
'2012-05-05' => array(
'suspension' => 52,
'transmission' => '58'
),
'2012-05-05' => array(
'suspension' => 44,
'transmission' => 21
I have done the following in my controller i want a $reportData variable to load the data.
public function loadReports(Request $request)
{
$data = ['2012-05-05','2012-05-06'];
$salesItems = array();
$orderItems = OrderItem::with('spare', 'order')->get();
foreach ($orderItems as $key => $orderItem) {
if ($orderItem->spare->retailer_id == Auth::user()->id) {
array_push($salesItems, $orderItem);
}
}
$categories = App\Categories::all();
foreach ($data as $date) {
foreach ($categories as $category) {
$categoryValue = 0;
foreach ($salesItems as $salesItem) {
if ($date == $salesItem->order->orderDate) {
$categoryValue += $categoryValue + $salesItem->subTotal;
}
}
//error appears as illegal offset type
$reportData[$date][$category]=$categoryValue;
}
}
return View::make('Retailer/reports')->with('categories', $categories)->with('reportData', $reportData);
}
I haven't tested it but looking at your code it seems that you're passing an object as array index key as 2nd level array index:
$reportData[$date][$category] = $categoryValue;
^^^^^^^^^ this is an object
Dump your $category in the foreach loop & check if that is the case: dd($category)
If you're using Eloquent & your Categories Model has a name property, you'll probably want to take each category name as index value:
$reportData[$date][$category->name] = $categoryValue;
The error is occurring due to the fact that you are trying to use an Object as the array's index.
As per the laravel documentation (https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Model.html#method_all) the all method you called here '$categories = App\Category::all();' would have returned an Eloquent Collection.
So when you iterated over the $categories array and referenced $category, you were referencing an object. In PHP an array can only be indexed by either an integer or a string. So you need to change the line of code where the error is to this
$reportData[$date][$category->someVar] = $categoryValue;
Where someVar is the name of a variable on the Eloquent model Category that references its name, such as 'suspension' etc.
While it doesn't answer your question you could use the Eloquent engine to make your life easier:
$orderItems = OrderItem::with('spare', 'order')->get();
foreach ($orderItems as $key => $orderItem) {
if ($orderItem->spare->retailer_id == Auth::user()->id) {
array_push($salesItems, $orderItem);
}
}
can be simplified (and made more efficient) with:
// Store the uid to save the call.
$user_id = Auth::user()->id;
// Apply the condition to the Eloquent query.
$orderItems = OrderItem::with(['spare' => function($query) use ($user_id) {
return $query->where('retailer_id', '=', $user_id);
}, 'order'])->get();
The other answers are correct, but you probably also want to initialise the $reportData array as before you start working with it.
i have a collection object
$di=array();
$products= $this->customerFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id','22');
foreach ($products as $key => $value)
{ # code... }
I want to know how to loop through this collection and create associative array ..and if result has multiple rows how to loop through it.
As final result i should get the array as
{key=>value, key1=>value1}
First of all, getCollection() already returns an array of elements of the given collection, with all its attributes (addAttributeToSelect('*')), so you are already receiving an array of objects rather than a multi-dimensional array.
In the simplest of all cases and if you need a JSON array containing all the products with all attributes, it would be as simple as this:
$jsonArray= json_encode($products); // converts all elements into a JSON representation
If you would need an associative array of elements rather than an array of objects, typecast the objects:
$assocArray= array();
foreach ($products as $product) {
$assocArray[]= (array) $product; // type-casting to array
}
If you want to iterate over each property of each product (I wouldn't know why you would want that), here's that version:
$assocArray= array();
foreach ($products as $product) {
$rowArray= array();
foreach ($product as $key => $val) {
$rowArray[$key]= $val;
}
$assocArray[]= $rowArray;
}
Hope that gives you an idea of how collections can be used in Magento work.
I have the function below in my model which return an array of data. I want to make another operation on each row and add the result to array of data before to return it.
function get_all_annonce()
{
$this->db->select(" * from annonce");
$this->db->order_by("annonce.DATEDEBUTANNONCE","asc");
$q=$this->db->get();
if($q->num_rows()>0)
{
foreach($q->result() as $row)
{
$data[]=$row;
//I try to add another result
$experience=$this->get_experience($row->NUMUSER);
$data['experience']=$experience;
}
return $data;
}
}
But I have an error when I try to access to $experience or $row->'experience' in my view. How can I fix it ?
The $data variable is defined in the wrong scope. You defined it inside the foreach loop but you try to return it after. Try adding $data = Array(); above the foreach.
In addition to the answer above.
First you have unnecessary assignments, you can do it in one line.
2nd - when you use [] - it will create index automatically and the row will be added as an array to that index. You get a multidimensional array( 0 => result 1, 1 => result 2 etc).
If you want to add the 'experience' key to the result, you cannot add it directly to data.
You get an array that will have keys 0,1,2,3,4 ... 'experience' as last key - each time it is overwritten.
One way would be to use a variable for key (or use for loop instead):
$i = 0;
foreach($q->result() as $row)
{
$data[$i]=$row;
$data[$i]['experience'] = $this->get_experience($row->NUMUSER);
}
If you used only [] for both, it would assign different key for each one every iteration.
I'm passing data from my controller:
$data = $this->post->get_post($postID);
$data['errors'];
$this->load->view('register_user.php', $data);
But For some reason, when trying to extract the array in the view, like so:
extract($data);
foreach ($data as $result)
{
echo $result,'<br>';
}
endforeach;
I get $data is null error.
What's the reason for the null array?
A couple things:
'post' is a model which i construct into the class,which pulls a certain row in a certain table that contains all of the details for a specific posts. When trying to echo the array in the controller, it shows.
could inserting a new key and value into the array ('errors'=> 0 ) the cause for the error?
You fetch your data in view like this.
$errors
Whatever you put in $data variable array and you pass $data variable to view, is "converted" in a such way that every element (index) is a variable in view.
So in controller we have $data['news'] = array(); $data['errors'] = array(); But in views we have only 2 variables that we can work with $news and $errors.
please make adjustment to your code as follows
$data['post'] = $this->post->get_post($postID);
var_dump($data['post']);
$this->load->view('register_user.php', $data);
and in view
foreach ($post as $result)...
You can access your data with array keys directly in view
For example:
if
$data = array(
'test1' => 'test1_data',
'test2' => 'test1_data'
);
In this case you can access $test1 directly like
<?php echo $test1; ?>