push array with php keys

1

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:tipoempleo
valorescategoria:porhoras,pordias,pormes

$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) {
["tipoempleo"]=>
    array(3) {
        [0]=>
        string(8) "porhoras"
        [1]=>
        string(6) "pordia"
        [2]=>
        string(6) "pormes"
    }
["ubicacion"]=>
    array(2) {
        [0]=>
        string(7) "interna"
        [1]=>
        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
source

2 answers

2

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
1

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

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

array_push($principal[0],"tipoempleo");
array_push($principal[1],"pordia","porhora");

print_r($principal);
    
answered by 24.08.2016 в 19:24