I'm trying to create an array inside an array, using a for loop - here's my code:
array(
'label' => 'Assign to user',
'desc' => 'Choose a user',
'id' => $prefix.'client',
'type' => 'radio'
'options' => array(
foreach ($clients as $user) {
$user->user_login => array (
'label' => $user->user_login,
'value' => $user->user_login,
),
}
)
)
Unfortunately this gives me a
"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')'"
For the line:
'options' => array(
I'm at a bit of a loss as to what has gone wrong - any help is much appreciated. $clients is defined elsewhere, so that is not the problem.
The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.
Due to operator precedence, you cannot put braces around the inner foreach loop. This is structured very much like the nested for loop. The outer foreach is iterating over the values in bvec , passing them to the inner foreach , which iterates over the values in avec for each value of bvec .
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it. Also you should avoid to open your php tags ten thousands times for a better visibility into your code :) <?
Your answerDeclare the $items array outside the loop and use $items[] to add items to the array: $items = array(); foreach($group_membership as $username) { $items[] = $username; } print_r($items); Hope it helps!!
That's invalid syntax. You'd have to build the "parent" portions of the array first. THEN add in the sub-array stuff with the foreach loop:
$foo = array(
'label' => 'Assign to user',
'desc' => 'Choose a user',
'id' => $prefix.'client',
'type' => 'radio',
'options' => array()
);
foreach ($clients as $user) {
$foo['options'][] = array (
'label' => $user->user_login,
'value' => $user->user_login,
);
}
You use foreach to access the data, not define it.
Try this:
array(
'label' => 'Assign to user',
'desc' => 'Choose a user',
'id' => $prefix.'client',
'type' => 'radio'
'options' => $clients
)
If you need to change the structure of the data for 'options', do this before defining the primary array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With