PHP create dynamic array in a multidimensional array

前端 未结 3 867
清酒与你
清酒与你 2021-01-29 09:36

I want to dynamic create an array based on a number inside a multidimensional array

here is the code

$meta_box = array(  
\'id\' => \'my-meta-box\',
         


        
3条回答
  •  悲哀的现实
    2021-01-29 09:44

    Here's a way to add each 'fields' sub array as a new array into the larger array

    $meta_box = array(  
    'id' => 'my-meta-box',
    'title' => 'Custom Input Fields',
    'page' => 'page',
    'context' => 'normal',
    'priority' => 'high');
    
    $fields = array();
    
    $numberOfArrays = 2;
    
    for($i = 1; $i <= $numberOfArrays; $i++){
        $fields[$i] = array (
                      array( //this array must be created dynamic 
                          'name' => 'Textarea',
                          'desc' => 'Enter big text here',
                          'id' => 'textarea' . $i, //id is textarea + number
                          'type' => 'textarea',
                          'std' => 'Default value'
                      )
                );
    }
    
    $meta_box['fields'] = $fields;
    
    echo '
    ';
    print_r($meta_box);
    echo '
    ';

    You'll get an output like this in your browser:

    Array
    (
        [id] => my-meta-box
        [title] => Custom Input Fields
        [page] => page
        [context] => normal
        [priority] => high
        [fields] => Array
            (
                [1] => Array
                    (
                                [name] => Textarea
                                [desc] => Enter big text here
                                [id] => textarea1
                                [type] => textarea
                                [std] => Default value
                    )
            [2] => Array
                    (
                                [name] => Textarea
                                [desc] => Enter big text here
                                [id] => textarea2
                                [type] => textarea
                                [std] => Default value
                    )
            )
    )
    

    Demo

提交回复
热议问题