0

Currently, I am trying to push multiple objects into an array($columnDefs) via a foreach loop. However, it seems not to be working. Could anyone advice what I did wrong?

$startingYear = 2012;
$endingYear = date('Y') + 1;
$yearRange = array();

for ($i = $startingYear;$i <= $endingYear;$i++)
{
    array_push($yearRange, $i);
}


$columnDefs = array(
    array('headerName' => 'Category', 'field' => 'category', 'width' => 180)
);

foreach($yearRange as $year){
   $columnDefs = array_merge(
       $columnDefs, 
       array(
           'headerName' => strval($year), 'field' => $year, 'width' => 120
       )
   );
}
1

1 Answer 1

1

For you to add new structures to your array, you will need to:

$columnDefs = array_merge(
       $columnDefs, 
       array(
           array('headerName' => strval($year), 'field' => $year, 'width' => 120)
       )
   );

In the adaptation I did to your code, above, you can see I an merging your previous columnDefs array with a new array structure that mimics your kick start for columnDefs.

If you do not tell it is an array it will always override your previous keys (because it does think it is keys and values its adding and not an array)

This will then start outputing:

Array ( 
[0] => Array ( [headerName] => Category [field] => category [width] => 180 )   
[1] => Array ( [headerName] => 2012 [field] => 2012 [width] => 120 ) 
[2] => Array ( [headerName] => 2013 [field] => 2013 [width] => 120 ) 
[3] => Array ( [headerName] => 2014 [field] => 2014 [width] => 120 )
...
Sign up to request clarification or add additional context in comments.

2 Comments

Your solution is working. However, my production site is running php 5.3.3 version which does not support [ ] arrays
Just replaced [ for array()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.