php 数组内的 Foreach 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14446174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Foreach loop inside array
提问by user319940
I'm trying to create an array inside an array, using a for loop - here's my code:
我正在尝试使用 for 循环在数组中创建一个数组 - 这是我的代码:
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 ')'"
“解析错误:语法错误,意外的 T_CONSTANT_ENCAPSED_STRING,期待 ')'”
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.
我对出了什么问题有点不知所措 - 非常感谢任何帮助。$clients 在别处定义,所以这不是问题。
回答by Marc B
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:
那是无效的语法。您必须先构建数组的“父”部分。然后使用 foreach 循环添加子数组内容:
$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,
);
}
回答by ste
You use foreach to access the data, not define it.
您使用 foreach 来访问数据,而不是定义它。
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.
如果您需要更改 'options' 的数据结构,请在定义主数组之前执行此操作。
回答by Cody Covey
You cannot use the foreach in the definition of the array. You can however put the $clientsvariable in the array itself or you can foreach outside the array to build the array to be inserted at the optionskey
您不能在数组的定义中使用 foreach。但是,您可以将$clients变量放在数组本身中,也可以在数组外 foreach 以构建要插入options键的数组

