I have array of objects users. Entity User has two fields: firstName and lastName;
In my controller I add all users to the some array which called employees.
$employees = array();
foreach($users as $user) {
$employees[] = $user->firstName;
}
How can i get on the view element of array by firstName.
I tried like this:
$employees['John'] but it doesn't work
Thanks in advance
The way that you are doing it you are just appending a string to an array. The keys of the array will be integers starting from 0.
To get the user first name as the index, set the Key of the $employees array to be the $user->firstName, then in that position store the object of the $user. Here is the code fixed:
$employees = array();
foreach($users as $user) {
$employees[$user->firstName] = $user;
}
After that you should be able to do $employees['John'].
Remember that to be able to use the array in the View you must pass the array to the view. Ex:
In your controller method you should have something like this:
return View::make('nameOfFile')->with('employees', $employees);
When you add the names to the array you will have something like this:
array(
[0] => "John",
[1] => "Martha",
...
)
You need to access the names by index and I would not suggest having name in the index, what if two users have the same name? You'll end up overwriting one in the array:
Array("John", "John", "Martha")
After having an array with the key as name you end up with:
Array(
[John] => someUser, // <- here you lost one John.
[Martha] => SomeUser,
)
You are appending to an ordinary array, which means that the array keys will automatically be integers in increasing order starting at zero. Suppose we have the "Alice" and "Bob" in the $users array, you code will yield an $employees array with two elements : $employees[Ø] = "Alice" and $employees[1] = "Bob".
To get the result you want you need to use the $user->firstName value as a key:
$employees = array();
foreach ($users as $user) {
$employees[$user->FirstName] = $user->firstName;
}
Although that wouldn't be very useful, I think what you actually meant to get is:
$employees = array();
foreach ($users as $user) {
// use the whole object for this user, not only the firstName field
$employees[$user->FirstName] = $user;
}
Related
I'm trying to get Count of a table called TestRunList that has the foreign key the same as another table called Testrun meaning i want to get count of how many testrunlist that single testrun has in the same page i did a forloop to get testrun id for each testrunlist but it didn't seem to work i get this error
Cannot use object of type stdClass as array
heres my Code in the controller
$data = DB::table('TestRun')->get();
$runs=array();
for ($i=0;$i<sizeof($data);$i++)
{
$testrunID=$data[$i]['TestRunID'];
$Testrunlist=TestRunList::where('test_run_id',$testrunID)->count();
$runs[$i]=[
'Countruns'=>$Testrunlist
];
}
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
$data is a Collection, you can't access using array syntax
$data = DB::table('TestRun')->get();
$runs = [];
$data->each(function ($row) use ($runs) {
$runs[] = [
'Countruns' => TestRunList::where('test_run_id',$row-> TestRunID)->count()
];
});
return view('management.testrun.testrun-list')
->with('data',$data)
->with('runs', $runs);
Always use
print_r($data);
if it's object run echo $data->username if array run echo $data['username'];
So you know what type of data you're dealing with.
I have an array of the names of my POST variables to use when I update a row in my database.
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
Using this style my table is called jobs and each value in the array is a column id.
I want to edit this array so each item (column id) contains a single _POST Value
Then I have a function that uses the variables to create generic queries.
function save_data($jobs) {
foreach ($jobs as $job)
{
$job[$job[$i]] = _$Post[$job];
or
Table_name[column] = cell value;
...
...
...
I would like to be able to save $values into the post variables associated to it. Something like
For example if I was going to manually create this array it would look like
$jobs = array('proposal_id' => '12345678','title_of_project' => 'aTitle','creator' => 'aUser','last_modified' => '0000-00-00','date_created' => '0000-00-00','price' =>'1000');
This should be what you're looking for:
$jobs = array( "proposal_id",
"will_provide",
"general_scope",
"per_bid",
"job_type");
$jobValues = array();
foreach($jobs as $job) {
$jobValues[] = isset($_POST[$job]) ? $_POST[$job] : null;
}
$jobs = array_combine($jobs, $jobValues);
I have produced an array of fruits stored somewhere. Say it looks like this
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
This array is then passed into a function that will return json-encoded data for an API.
First, I wanted to be able to return a list of all the types of fruits I have
{"fruits":["apples", "oranges", "bananas"]}
I used this to accomplish it
echo json_encode(array("scripts" => array_keys($scripts)));
Now, I would like each type of fruit to be contained in its own hash, as such
{"fruits":
[
{name: "apples"
},
{name: "oranges"
},
{name: "bananas"
]
}
This way I can add additional fields to each fruit object without breaking existing code that may be using previous versions of this API (eg: if I decided to add the fruit counts in there as well).
Seeing how I can just create a new array and assign my list of fruits to a key called "fruits", I tried to do the same for each inner hash:
$myFruits = array("apples"=>1, "oranges"=>3, "bananas"=>5);
$data = array();
foreach ($myFruits as $key => $value) {
// initialize an associative array for each fruit
$val = array();
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
}
// assign list of fruits to "fruits" key
$outData = array("fruits" => $data);
echo json_encode($outData);
But I get this instead
{"fruits":[[{"name":"apples"}],[{"name":"oranges"}],[{"name":"bananas"}]]}
There are extra square braces around each fruit hash, which I assume is because I'm using an array to store each key-value pair.
How would I get my desired output?
You're close to knowing what you're doing wrong. You're creating an array, and then just using it to add one item (another array) to it.
// initialize an associative array for each fruit
$val = array(); // this guy here is unnecessary!!
array_push($val, array("name" => $key));
// add it to the list of fruits
array_push($data, $val);
Instead, just push each individual array onto $data directly like this:
array_push($data, array("name" => $key));
DEMO
You are creating an extra level in your array, simply push a new array onto $data in each iteration:
foreach ($myFruits as $key => $value) {
$data[]=array("name" => $key, "count" => $value);
}
*edited as per your comment
I have an issue on how can I update my Previous array ?
What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:
//get the array of items (you will want to update) from the session variable
$old_items = \Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
\Session::put('items',array_merge($old_items,$new_item));
You can use Session::forget('key'); to remove the previous array in session.
And use Session::push to add new items to Session.
I have two arrays. The first one contains an id, username, and password from the database and it looks something like this:
Array ( [id] => 3 [username] => Scott [password] => new )
The second array is
get_class_vars();
and obviously contains all of the classes vars which are id, username, etc..
How can I go about comparing the keys from both arrays and then if the keys are the same, for example username=username, how can I assign the values of username to the class property username? it's worth noting that I've already instantiated the class and am calling the methods from test.php:
// authenticate returns user info from the db
$user = new User();
$find = $user->authenticate($username, $password);
$user->instantiate($find) // this is the method that I need to create
// in user.php to assign the user properties
Hopefully this makes sense. I been trying to come up with a solution for hours. If you need any clarification please let me know.
$common_keys = array_intersect(array_keys($array), array_keys(get_class_vars($object));
foreach($common_keys as $key) $object->$key = $array[$key];
Try this:
foreach(get_class_vars() as $key->$value)
$array[$key] = $value;
This gets the key from get_class_vars() and sets that value in $array (your other array) to $value.
PHP supports storing variable and function names in other variables. Using that, you could iterate over all keys of your array, check if the key exists as an attribute of your User object, and if so, replace the value in the object with the one from your array:
foreach ($array as $key => $value) {
if (isset($user->$key)) {
$user->$key = $value;
}
}
So for Array ( [username] => JohnSmith ) it will check isset($user->username) and then assign $user->username = 'JohnSmith'.