Array_push in php multidimensional associative arrays

Asked

Viewed 449 times

0

I started an array ($arrDados=array();) and now I need to add information (array_push) so that I can access the information later on as follows:

colA1 = $arrDados['NumeroEmpenhoAno']['code'];
colA2 = $arrDados['NumeroEmpenhoAno']['size'];

colB1 = $arrDados['UnidadeOrc']['code'];
colB2 = $arrDados['UnidadeOrc']['size'];

What would be the array_push code to be able to access this array in the above structure?

I’m trying the code below, but it’s wrong:

$arrDados=array();
array_push($arrDados,array('NumeroEmpenhoAno' => array('code' => 0,'size' => 1)));
array_push($arrDados,array('UnidadeOrc' => array('code' => 1,'size' => 2)));

The way I’m doing it, I’m having to access it the following way:

colA1 = $arrDados[0]['NumeroEmpenhoAno']['code'];

but I want to:

colA1 = $arrDados['NumeroEmpenhoAno']['code'];

That is, without indexes.

1 answer

1

You don’t need the array_push, you can just do:

$arrDados = array();

$arrDados += array('NumeroEmpenhoAno' => array('code' => 0,'size' => 1));
$arrDados += array('UnidadeOrc' => array('code' => 1,'size' => 2));

However one of the most common ways of doing:

$arrDados = array();

$arrDados['NumeroEmpenhoAno'] = array('code' => 0,'size' => 1);
$arrDados['UnidadeOrc'] = array('code' => 1,'size' => 2);

Both can be accessed by $arrDados['UnidadeOrc']['code'], without the use of [1].

Test this.

  • Perfect, thank you, worked perfectly!

Browser other questions tagged

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