push array with php keys


Good morning.

I am trying to create an array with values grouped by categories, by AJAX I receive two variables one contains a string with the name of the category and the other contains an array with the values of the category for example:


$categoria = $_POST["nombrecategoria"];
$valores = $_POST["valorescategoria"];

$categorias = array();

Since there are several categories I need to differentiate them in the array, how do I use array_push to add categories to the array? Or should it be done in another way?

Something like that

array(2) {
    array(3) {
        string(8) "porhoras"
        string(6) "pordia"
        string(6) "pormes"
    array(2) {
        string(7) "interna"
        string(7) "externa"


I hope I can have some kind of orientation, I must also be updating the array, that is to say, I can use a job to remove a value or add another, it is the best way to recommend this process or there is a better one, thank you for your attention.

asked by DIANGA 18.08.2016 в 18:26

2 answers


Unless you are not understanding the question, you are trying to add elements to the array as you go "receiving", but considering that it is an associative array you do not need to use array_push (), simply add the key and its values directly:

$categorias = [];

// Recibes la primera categoría y sus valores
$categoria = 'tipoempleo';
$valores = ['porhoras', 'pordias', 'pormes'];

// Los agregas al arreglo
$categorias[$categoria] = $valores;

// Recibes la segunda categoría y sus valores
$categoria = 'ubicacion';
$valores = ['externa', 'interna'];

// Los agregas al arreglo
$categorias[$categoria] = $valores;

// así sucesivamente
answered by 18.08.2016 в 18:55

You can use the array_push function, I'll give you an example:

$principal = array($categoria,$valores);


answered by 24.08.2016 в 19:24