I am pulling a source of data from an API, and using json_decode, converting it to an array. The idea is to push this data to a template and loop it to display rows in a table.
I found that unlike most other MVC frameworks, Silverstripe does not seem to have a native way of pushing an array to the template engine. I found many posts and snippets for doing this by manually converting arrays to ArrayLists and ArrayData objects. But no examples covered much past single dimension arrays.
This array is around 5 levels deep in some places. And some element keys are not known (dates/ids). In any case I managed to manually create a ArrayList object where each level from the array is represented by an ArrayData object.
Here is the code:
$rowTemp["cell1"] = $dayData['item']['one'];
$rowTemp["cell2"] = $dayData['item']['two'];
$rowTemp["cell3"] = $dayData['item']['three'];
$rowTemp["cell4"] = $dayData['item']['four'];
$rowTemp["cell5"] = $dayData['item']['five'];
$rowTemp["cell6"] = $dayData['item']['six'];
$rowTemp["cell7"] = $dayData['item']['seven'];
$rowTemp["cell8"] = $dayData['item']['eight'];
$rowTemp["cell9"] = $dayData['item']['nine'];
$rowTemp["cell10"] = $dayData['item']['ten'];
$finalRows[$datestamp] = new ArrayData($rowTemp); // Had to do this just to get the key "rows" in the ArrayData structure
// Did some stuff with totals and averages in the above fasion
$finalStructure = new ArrayData(array(
new ArrayData($finalRows),
new ArrayData($finalTotals),
new ArrayData($finalAverages)
));
$mpqTableRows = new ArrayList(array($finalStructure));
This is what I ended up with:
ArrayList Object
(
[items:protected] => Array
(
[0] => ArrayData Object
(
[array:protected] => Array
(
[rows] => ArrayData Object
(
[array:protected] => Array
(
[1379073600000] => ArrayData Object
(
[array:protected] => Array
(
[cell1] => 5618
[cell2] => 6840
[cell3] => 517.4
[cell4] => 632.1
[cell5] => 517.4
[cell6] => 632.1
[cell7] => 8.98
[cell8] => 8.98
[cell9] => 205.00
[cell10] => 204.00
)
Now I am calling this objected on my template using a method in the controller that just returns it. It seems to pull the object. But I cannot effectively loop through it to the point I can see rows.
Even when I break this object down and send just the "rows" element to the template, <% loop getRows %> returns just one item when there are many if I dump the same object. I assume this is due to the fact that the contents of that ArrayData object is one Array.
If all this is confusing, welcome to the last two days of work and loving memories of Symfony/Twig's {{ this.is.a.six.level.array }} simplicity.
The Question How do you get multi dimensional arrays from PHP accessible by the templates. Any examples online, even existing modules, would be great.