How to dynamically set a parent table when accessing a collection? - php

I'm trying to fetch data from dynamically different tables depending on which user is logged on and if he is allowed to edit said table, what I thought was going to work was this:
$colaboradores = Colaboradore::where('email', '=', Auth::user()->email)->first();
$tables = DB::connection('mysql2')->select("SHOW TABLES LIKE 'intervencoes\_%'");
foreach ($tables as $object) {
$arrays[] = (array)$object;
}
foreach ($arrays as $array) {
$string = implode('', $array);
$test = $colaboradores->Niveis->$string->id;
}
And it outputs an error on the last bit of code saying
"Trying to get property 'id' of non-object"
I have been looking around for hours but couldn't find anything related.
This is all inside a livewire component by the way.
Thanks in advance.
Edit:
dd($colaboradores->Niveis)
dd($colaboradores->Niveis->$string)

Since $colaboradores->Niveis->$string returns a Collection, you need to iterate over it to get results.
$test = [];
foreach ($colaboradores->Niveis->$string as $obj) {
$test[] = $obj->id;
}
Then you can check the IDs in $test with dd($test); for example.
This can cause a problem if $obj is not a real object, so you could check it with:
if (!is_object($obj)) {
//Do something - Not an object!
}

Related

Creating arrays within arrays without creating keys first

This is how I used to create keys that didn't exist inside an array when looping through data:
$array = [];
foreach ($results as $result) {
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
$array[$result->id][] = $result->value;
}
A colleague at work does the following. PHP doesn't error but I am not sure if it's a feature of PHP or if it's incorrect:
$array = [];
foreach ($results as $result) {
$array[$result->id][] = $result->value;
}
Is it incorrect for me to do the above?
if condition you put in your code is unnecessary. Let me explain.
if (!isset($array[$result->id])) {
$array[$result->id] = [];
}
This mean if $array[$result->id] is not exist than you are define it as an array, however $array[$result->id][] it self create new array if not existing without throwing any error. So no need to use if condition error. In conclusion, both code are correct, just you are using unnecessary if condition.

Merging two queries to one JSON object

I have two queries:
1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();
I'm trying to output the data in this JSON format:
{
[
{
id:12,
title:"Meet Messi",
image_url:"http://dsadsa.dsadsa",
previewImageUrl:"http://kdjfla.com"
is_open:"true"
requirements: [
{
id: 123,
title:"kiss Messi",
is_complete: true
}
]
}
]
}
}
I created two models (one for each query).
This is what I've done so far:
$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();
$return_array = array();
foreach ($result as $value)
{
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$return_array[] = $wishes_model;
}
return $return_array;
How to i insert the requirements result to create this JSON?
First, create your wishes array as an associative array, with the ID as the key:
$wishes_array = array();
foreach ($results as $value) {
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$wishes_array[$value['id']] = $wishes_model;
}
Then you can add the requirements to the appropriate wish:
foreach ($requirements_results as $req) {
$wishes_array[$req['wish_id']]->requirements[] = $req;
}
I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.
I have couple of question but for now i am gonna guess.
You can try array_merge but it will overwrite same keys.
If you don't want that you can add prefix to keys and then merge both array.
And i think rest of the solutions you already have in here.
Hi like you have 2 results say result1 and result2
you can make 2 foreach loop for each and store them in two different array and then
you make pass it in result and encode it.
see how it works:
foreach ($result1 as $res)
{
$result_s1[]=$res;
}
foreach($result2 as $cmd)
{
result_s1[]=$cmd;
}
$resultdata[]=array_merge($result_s1,$result_s2)

Laravel 4 DB::table - Foreach

I'm trying to run a sql query and return all values into an array of the tables names...
This is what I have so far:
$vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->get();
$row = $vehiclemodeldata->row();
foreach ($row as $key => $value){
$viewData['vehiclemodeldata_'.$key]= $value;
}
What are your throughts?
EDIT
I've tried this it seems to bring it back in an array but I can't access the array for some reason.
$VehicleModel = DB::table('model')->where('model_id', $viewData['model_id'])->get();
Thanks
This is because $vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->get(); actually returns an object instead of an array.
Your foreach loop is correct. You can later access properties in the array by using syntax like this $viewData['vehiclemodeldata_1']->yourProperty; which is used to access properties of objects.
Hope it answers the question.
$vehiclemodeldata = DB::table('model')->where('model_id', $viewData['model_id'])->first();
$viewData['vehiclemodeldata'] = $vehicle->toArray();
But why would you like to do this?
I would pass query result directly to view instead
$vehicle = DB::table('model')->where('model_id', $id)->first();
return View::make('whateverview', compact('vehicle'));
// view file
Model: {{ $vehicle->model }}
...

for loop and appending to an array in PHP

I have the following code:
$items = array();
foreach($following as $storeOwner)
{
array_push($items, $productRepository->mostRecentItem($storeOwner->getId(), 5));
}
I am trying to append the results of
$productRepository->mostRecentItem($storeOwner->getId(), 5)
to $items. How do I do so? Why doesn't the above code work?
Try this:
$items = array();
foreach($following as $storeOwner)
{
$items[] = $productRepository->mostRecentItem($storeOwner->getId(), 5);
}
Also, take a look to the result of the mostRecentItem Method... .
var_dump you different objects and return values to make sure that contain what you think they should contain. The code looks "correct" so it's probably the objects and values that are not.

Accessing an array in an object

If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array

Categories