数组内的 Foreach 循环 [英] Foreach loop inside array

查看:38
本文介绍了数组内的 Foreach 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 for 循环在数组中创建一个数组 - 这是我的代码:

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

"解析错误:语法错误,意外的T_CONSTANT_ENCAPSED_STRING,期待')'"

"Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')'"

对于行:

'options' => array( 

对于出了什么问题,我有点不知所措 - 非常感谢您的帮助.$clients 是在别处定义的,所以这不是问题.

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.

推荐答案

那是无效的语法.您必须首先构建数组的父"部分.然后使用 foreach 循环添加子数组内容:

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

这篇关于数组内的 Foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆