0

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

1
  • Can we see the $users array please also a $employers Commented Aug 14, 2014 at 7:45

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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,
)

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.