[英]PHP: Need an alternative to eval() for dynamically building multidimensional array
好吧,所以我知道使用eval()並不是很好,但我無法為我的問題找到更好的解決方案,直到最近,沒有性能原因不使用它。 但是,我現在正在將足夠的數據傳遞給函數,因為它正在花費不可接受的時間。
被調用的函數是:
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;
}
它被稱為這樣:
makeAMultiDimensionalArrayWithSumsBasedOnMultipleFields($data, $dimensionArray, $sumArray, $staticArray);
傳遞給函數的變量類似於:
$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");
所以我想重寫函數,以便我不再使用eval()。 我花了相當多的時間在這上面,覺得是時候尋求一些建議了。
目標是獲取一個數組數組,並根據$ dimensionArray中的維度將其轉換為多維數組。
我現在不想向你提供太多細節,所以請問你是否需要更多或有任何其他問題
哇,好的。 第一次通過我錯過了你的索引連接。 嘗試這個:
if ($allFieldsPresent) {
$keys = array();
foreach ($dimensionFieldNames as $keyFieldName) {
$keys[] = $row[$keyFieldName];
// lets sum values
foreach ($sumFieldNameArray as $sumFieldName)
self::deepAssign($outArray, $keys, $sumFieldName, $row[$sumFieldName], true);
foreach ($staticFieldNameArray as $staticFieldName)
self::deepAssign($outArray, $keys, $staticFieldName, $row[$staticFieldName]);
}
}
protected static function deepAssign(&$array, $keys, $fieldName, $value, $sum = false) {
$target =& $array;
foreach ($keys as $key) {
if (!isset($target[$key]))
$target[$key] = array();
$target =& $target[$key];
}
if($sum)
$target[$fieldName] += $value;
else
$target[$fieldName] = $value;
}
你應該看看create_function()
(這里是docs )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.