Assuming you are trying to map Columns from the resulting rows such that:
Row | Column 1 | Column 2 1 | Value 1 | Value 2 2 | Value 2 | Value 2
Results in:
$rows = array( 1 => array( 'Column 1' => 'Value 1', 'Column 2' => 'Value 2' ), 2 => array( 'Column 1' => 'Value 1', 'Column 2' => 'Value 2' ), );
If your PDO returns the values in numerical position, you can do this:
$columns = array( 'Column 1', 'Column 2' ); $rows = array_map(function($row) use ($columns) { return array_combine($columns, $row); }, $resultSet);
Or, if the $resultSet
is associative, and you want to keep the names:
$columns = array_flip(array( 'Column 1', 'Column 2' )); $rows = array_map(function($row) use ($columns) { return array_intersect_key($row, $columns); }, $resultSet);
OR, if your PDO returns them in an Associative array, but the Column names need to be change:
$columns = array( 'Column 1' => 'Key 1', 'Column 2' => 'Key 1' ); $rows = array_map(function($row) use ($columns) { $return = array(); foreach($columns as $from => $to) { $return[$to] = !empty($row[$from]) ? $row[$from] : NULL; } return $return; }, $resultSet);
That last one would work for either situation, really, as it will take the value at $row[$from]
and place it at $result[$to]
, which would account for numerical indices or string indices. Also, the empty()
check will suppress PHP errors, and will ensure that you have a value at each position.
SELECT a as b
orSELECT a b
) and then usefetchAll()
. Not sure what other APIs have a method like that.\$\endgroup\$