Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: Need an alternative to eval() for dynamically building multidimensional array
    text
    copied!<p>Okay, so I know that using eval() isn't great, but I haven't been able to come up with a better solution to my problem, and until recently, there wasn't a performance reason not to use it. However, I am now passing enough data to the function that it is taking unacceptably long.</p> <p>The function that is being called is:</p> <pre><code>public static function makeAMultiDimensionalArrayWithSumsBasedOnMultipleFields($inArray, $dimensionFieldNames, $sumFieldNameArray, $staticFieldNameArray = array()) { $outArray = array(); // Just in case the array has indices, sort it so array_pop works as expected. ksort($dimensionFieldNames); foreach ($inArray as $row) { // make sure each row in the inArray has all keys specified by $dimensionFieldNames $allFieldsPresent = TRUE; foreach ($dimensionFieldNames as $keyFieldName) { if (!array_key_exists($keyFieldName, $row)) { // Note that alternatively we could set the field to a specified default value. $allFieldsPresent = FALSE; } } if ($allFieldsPresent) { $indexString = ''; $keyFieldNameArrayCopy = $dimensionFieldNames; foreach ($dimensionFieldNames as $keyFieldName) { $indexString .= "['" . $row[$keyFieldName] . "']"; // lets sum values foreach ($sumFieldNameArray as $sumFieldName) { eval ('$outArray' . $indexString . '[' . $sumFieldName . '] += $row[' . $sumFieldName . '];'); } foreach ($staticFieldNameArray as $staticFieldName) { eval ('$outArray' . $indexString . '[' . $staticFieldName . '] = $row[' . $staticFieldName . '];'); } } } } return $outArray; } </code></pre> <p>It is being called like this:</p> <pre><code>makeAMultiDimensionalArrayWithSumsBasedOnMultipleFields($data, $dimensionArray, $sumArray, $staticArray); </code></pre> <p>And the variables being passed to the function are similar to:</p> <pre><code>$dimensionArray = array("firstLevelID", "secondLevelID", "thirdLevelID", "fourthLevelID", "fifthLevelID"); $sumArray = array("revenue", "cost", "profit", "sales", "inquires", "cost", "walkins"); $staticArray = array("date", "storeID", "storeName", "productID", "productName", "managerID", "managerName", "salesperson"); </code></pre> <p>So I want to rewrite the function so that I'm not using eval() any more. I've spent a considerable amount of time on this, and feel that it's time to seek some advice.</p> <p>The goal is to take an array of arrays, and turn it into a multidimensional array based on the dimensions in the $dimensionArray.</p> <p>I don't want to bore you with too many details right now, so please ask if you need more or have any other questions</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload