How to add an array within an array?

Asked

Viewed 906 times

1

$regras = array(
    array(
        'field' => 'cpf',
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
));
// o array $maisUmCriterio tem que ser inserido dentro de $regras
$maisUmCriterio =    
    array(
        'field' => 'nome',
        'label' => 'NOME',
        'rules' => 'required|trim'
);

// já tentei fazer

$regras = $regras + $maisUmCriterio;

// mas não funciona, preciso que o array $regras fique assim :

$regras = array(
    array(
        'field' => 'cpf',
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
    ),
    array(
        'field' => 'nome',
        'label' => 'NOME',
        'rules' => 'required|trim'
    )
);

1 answer

1

You are missing something, which is "[]" at the end of the variable name where you want to insert the new array:

We have:

$regras = array(
    array(
        'field' => 'cpf', 
        'label' => 'CPF',
        'rules' => 'required'
    ),
    array(
        'field' => 'senha',
        'label' => 'SENHA',
        'rules' => 'required|trim'
    ),
);

To add another array within this array:

$regras[] = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);

DEMONSTRATION

You actually have more ways:

array_unshift, attaches to the beginning of the array:

$add = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);

array_unshift($regras, $add);

array_push, adionas at the end (similar to the first example I gave):

$add = array(
    'field' => 'nome',
    'label' => 'NOME',
    'rules' => 'required|trim'
);

array_push($regras, $add);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.