Foreach loop inside array

后端 未结 3 1520
灰色年华
灰色年华 2020-11-27 06:02

I\'m trying to create an array inside an array, using a for loop - here\'s my code:

    array(
    \'label\' => \'Assign to user\',
    \'desc\' => \'C         


        
相关标签:
3条回答
  • 2020-11-27 06:03

    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,
        );
    }
    
    0 讨论(0)
  • 2020-11-27 06:11

    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.

    0 讨论(0)
  • 2020-11-27 06:29

    You cannot use the foreach in the definition of the array. You can however put the $clients variable in the array itself or you can foreach outside the array to build the array to be inserted at the options key

    0 讨论(0)
提交回复
热议问题