J'ai deux méthodes vraiment cool qui fonctionnent ensemble pour votre but (et ses variations).
/**
* Pivots a 2 dimensional array.
*
* Turns the column names in a two dimensional array into the rows,
* using the original array's row indexes as column names. The input
* array and its rows may be integer-indexed or a hash.
*
* You can optionally specify a column or list of columns to return as rows
*
* Example -
* <pre>
*
* input:
* $aIn => array([0] => array([name] => 'John Doe', [phone] => '555-1000', 'happy'),
* [1] => array([name] => 'Fred Doodle', [phone] => '555-2000', 'sad', [title] => 'President'),...
*
* output:
* array([name] => array([0] => 'John Doe', [1] => 'Fred Doodle',...),
* [phone] => array([0] => '555-1000', [1] => '555-2000',...),
* [0] => array([0] => 'happy', [1] => 'sad',...),
* [title] => array([1] => 'President'))
*
* </pre>
* @param array $aInput A two dimensional array
* @param mixed $mColumns An array of columns or single column name. If nothing
* passed, then all columns from each input row will become rows
* in the output array.
* @return array Pivoted array !!! If a single column name is passed in $mColumns
* The return will be a one-dimensional array; you will get back
* an array of the values for that column.
*/
static function pivot($aIn, $mColumns = null) {
// Initialize the output
$aOut = array();
/*
* If input list of column names, then initialize, in case the
* input array is empty or doesn't have those columns
*/
if (is_array($mColumns) && !empty($mColumns)) {
foreach ($mColumns as $col) {
$aOut[$col] = array();
}
}
/*
* Output array needs to be passed inside an array to be passed by reference.
*/
// TODO As of PHP 5.2.3, could replace callback arg below with simply "xarray::pivot_row", but production uses 5.1.6
array_walk($aIn, array("xarray", "pivot_row"), array(&$aOut));
return (empty($aOut) || is_null($mColumns) ? $aOut : (is_array($mColumns) ? array_intersect_key($aOut, array_flip($mColumns)) : $aOut[$mColumns]));
}
public static function pivot_row($aRow, $mKey, $aSpec) {
foreach ($aRow as $k => $v) {
$aSpec[0][$k][$mKey] = $v;
}
}
Suppression de nouvelles lignes vides de sens triche. Je pense que par "une ligne" l'OP signifiait "une déclaration". –