Populate array dynamically

Asked

Viewed 803 times

1

Guys, I need help. I have the following fixed structure in php:

'labels' => array('Jan','Fev','Mar')......

But I want to fill these internal values of the array dynamically, or I will search the database for certain random months and use inside. But I try to do this:

$meu_array = array();
// preencho o array

'labels' => array($meu_array);

But it doesn’t work. How do I do it?

3 answers

1

If you make the correct array with the data coming from the database, it is to work like your example of the months. I made an example here more or less.

$a = array('labels' => array('jav', 'fev', 'marc'));
$my_array = array('jav', 'fev', 'marc');
$new_array = array('labels' => $my_array);

Will stay like this:

Array
(
    [labels] => Array
    (
        [0] => jav
        [1] => fev
        [2] => marc
        )

    )

segundo array 
Array
(
    [labels] => Array
    (
        [0] => jav
        [1] => fev
        [2] => marc
        )

    )

Looked just like that. If you are not able to access your second array in the indexes it is because you are not filling correctly.

Always check how the array is getting var_dump, print_r if you are unable to access content.

1

You can create a dynamic array using "[]":

$array['labels'][] = 'Jan';
$array['labels'][] = 'Mar';
$array['labels'][] = 'Fev';

var_dump($array);

outworking:

array (size=1)
  'labels' => 
     array (size=3)
       0 => string 'Jan' (length=3)
       1 => string 'Mar' (length=3)
       2 => string 'Fev' (length=3)

0

When I fill array dynamically I do in matrix form, which transfer the table from the database directly to the array:

$new_table = array();

  for($a = 0; $a < 2; $a++){
  //Avança as linhas
  $new_table[$a][$b] = $varbanco['Meses'];
  $new_table[$a][$b+1] = $varbanco['Ano'];
  $new_table[$a][$b+2] = $varbanco['Dia'];
}

Of course there must be a simpler way, but this way makes it possible to add future information if necessary

Browser other questions tagged

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