Question

I have some tabular data in a 2D array. I partitioned the tabular data by equality on a certain column value. All the rows of the tabular data with equal column values were placed together in a new 2D array, and all the 2D arrays were stored in a 3D array.

Now I would like to sort the rows in each 2D partition by the values of a column, and order the 2D partitions in the 3D array by their equal column values.

I wrote the following function to sort the partitioned data:

function sortPartitions($tableCol, $partitionCol, $partitioned3dData) {

  foreach($partitioned3dData as $table) {
    usort($table,
          function($a,$b) {
            return genCmp($a[$tableCol],
                          $b[$tableCol]);
          });

  }
  usort($partitioned3dData,
        function($a,$b) {
          return genCmp($a[0][$partitionCol],
                        $b[0][$partitionCol]);
        }); 

  return $partitioned3dData;
}

function genCmp($a,$b) {
  if($a==$b)
    return 0;
  else
    return ($a<$b) ? -1 : 1;
}

When I ran the code I got the following error:

Notice: Undefined variable: partitionCol in /path/to/file.php on line 1337.

Why was $tableCol's value passed into the anonymous function's closure successfully but $partitionCol's value caused an error?

Was it helpful?

Solution

You need to pass it into the closure scope using use:

usort($partitioned3dData,
        function($a,$b) use ($partitionCol) {
          return genCmp($a[0][$partitionCol],
                        $b[0][$partitionCol]);
        }); 

OTHER TIPS

You have to use both arguments for the two anonymous functions. I get an Undfinied variable error if I only use the $partitionCol.

function sortPartitions($tableCol, $partitionCol, $partitioned3dData) {

    foreach($partitioned3dData as $table) {
        usort($table, function($a,$b) use ($tableCol) {
            return genCmp($a[$tableCol], $b[$tableCol]);
        });
    }

    usort($partitioned3dData, function($a,$b) use ($partitionCol) {
        return genCmp($a[0][$partitionCol], $b[0][$partitionCol]);
    }); 

    return $partitioned3dData;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top