2

I have another problem. I have to tables: 1 - with users 2 - with groups. Tables are connected with id of groups - groupid from table 1 is connected with id of group from table 2.

I wanted to create list of options using this code:

echo $this->Form->input('Priority', array(
'label' => 'Group', 
'options' => $groups_array
)); 

Now the $group_array should look

like array('1' => 'Admin', '2' => 'User');

I've tried to push group id and group name via this code, but it doesn't work properly (it adds group with ID lowered by 1 - i assume that the ID isn't id of group but ID of name position in array $group_array.

$groups_array = array();

foreach($groups as $group):

echo $group['Group']['ID']; echo $group['Group']['Name'];

array_push($groups_array, $group['Group']['ID']=$group['Group']['Name']);

endforeach;

How can i fix that?

1 Answer 1

1

Rather than using array_push(), since you intend to set the array index directly from $group['Group']['ID'], use that value as the index to $groups_array in the assignment:

$groups_array = array();
foreach ($groups as $group) {
  // assign a new key $group['Group']['ID'] directly
  $groups_array[$group['Group']['ID']] = $group['Group']['Name'];
}

Here's what went wrong:

The "reduced by one" issue you describe was sort of a coincidence of having users with ids 1, 2 appending to an array. The first was appended at index 0 and the second as 1. If the array started non-empty, the users would have been appended to the end of it.

When you did

array_push($groups_array, $group['Group']['ID']=$group['Group']['Name']);

...PHP managed to assign the Name key into the existing ID key, overwriting the ID with the name, and then return that value into the second parameter of array_push(). So really what PHP eventually saw was

array_push($groups_array, 'Admin');
array_push($groups_array, 'User');
Sign up to request clarification or add additional context in comments.

1 Comment

You are awesome :o Thanks for solving my problem :) Have a nice day!

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.