Editing a multidimensional array with [index] es, not just [name] s

public $form = array (  
    array(  
        'field' => 'email',  
        'params' => array(  
            array(  
                'rule' => 'email',  
                'on' => 'create',  
                'required' => true,  
                'error' => 'The email is invalid!'  
            ),  
            array(  
                'rule' => 'email',  
                'on' => 'update',  
                'required' => false,  
                'error' => 'The email is invalid!'  
            )  
        )  
    )  
);


public function onlyNeeded($action) {
    $form = $this->form;
    $action = $this->action;

    foreach ($form as $formelement) {
        $field = $formelement['field'];
        $paramsgroup = $formelement['params'];
        if ($paramsgroup['on'] != $action) {
            form = removeparamsgroup($form, $action);
            }
        }
    return $form;
}

      

How to make a function removeparamsgroup()

?

There is [index] es, not just [name] s!

Do you know what I mean?

array (array (twice!

0


a source to share


3 answers


If you get the key of the array in a foreach loop, you can turn off the correct array index using this. You also need to iterate over every parameter of each form element, which you did not do in your example.



public function onlyNeeded($action) {
    $form = $this->form;

    //get $formelement by reference so it can be modified
    foreach ($form as & $formelement) {

        //$key becomes the index of current $param in $formelement['params']
        foreach ($formelement['params'] as $key => $param) {
           if ($param['on'] != $action) {
               unset($formelement['params'][$key]);
           }
        }
    }
    return $form;
}

      

+1


a source


unset ($ form ['params'])? What do you mean by deletion?



0


a source


Try it.

function onlyNeeded($action) {
    $form = $this->form;

    foreach ($form as &$formelement) {
        foreach ($formelement['params'] as $key => $paramsgroup)
        {
            if ($paramsgroup['on'] != $action)
                unset($formelement['params'][$key]);
        }
    }
    return $form;
}

      

Don't forget and sign the first foreach loop, otherwise it won't work. Unsigned and unsigned foreach copies each item rather than returning a reference.

0


a source







All Articles