PHP: Convert Array to Hash

A couple of little functions to help convert arrays into a hash table like array structure.

First off, to convert a series of parallel arrays into a hash

function columnsToHashTable($columnNames){

	$retVal = array();
	$arg_list = func_get_args();
	$num_args = func_num_args();
	$num_cols = count($columnNames);

	if( ($num_args - 1) !== $num_cols ){
		return FALSE;
	}

	for ($i = 0; $i < $num_cols; $i++) {

		$columnName = $columnNames[$i];
		$columnVals = $arg_list[$i+1];

		$num_rows = count($columnVals);

		for ($j = 0; $j < $num_rows; $j++) {
			$retVal[$j][$columnName] = $columnVals[ $j ];
		}

	}

	return $retVal;

}

Which can be used like this ...

$columns = array('id', 'firstname', 'lastname');
$ids = array('1', '2', '3');
$firstnames = array('John', 'Dave', 'Paul');
$lastnames =  array('West', 'Smith', 'Jones');
$hash = columnsToHashTable( $columns, $ids, $firstnames, $lastnames );

And will give you a return value like this ...

Array
(
    [0] => Array
        (
            [id] => 1
            [firstname] => John
            [lastname] => West
        )

    [1] => Array
        (
            [id] => 2
            [firstname] => Dave
            [lastname] => Smith
        )

    [2] => Array
        (
            [id] => 3
            [firstname] => Paul
            [lastname] => Jones
        )

)

And a second function which will convert a series of rows into the same format as above ...

function rowsToHashTable($columnNames){

	$retVal = array();
	$arg_list = func_get_args();
	$num_args = func_num_args();
	$num_cols = count($columnNames);

	for ($i = 1; $i < $num_args; $i++) {

		$rowVals = $arg_list[$i];

		if( $num_cols !== count($rowVals) ){
			return FALSE;
		}

		$retVal[] = array_combine($columnNames, $rowVals);

	}

	return $retVal;

}

Which can be used like this ...

$columns = array('id', 'firstname', 'lastname');
$row1 = array('1', 'John', 'West');
$row2 = array('2', 'Dave', 'Smith');
$row3 = array('3', 'Paul', 'Jones');
$hash = rowsToHashTable( $columns, $row1, $row2, $row3 );

 

 

By Karl Payne

Comments

There are no comments, don't be shy, somebody has to be first.

Leave a comment