Generating array with dynamic number of values

Hi, I’m trying to create a method that outputs an array in this format:


Array
(
    [0] => Array
        (
            [name] => home
            [id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [name] => about
        )
)

The problem is I want to generate the number of keys in the array dynamically. So instead of just writing array(‘id’ => $idValue, ‘name’ => $nameValue); the number of keys has to be flexible, since this method is used to generate a table with x number of columns.

So far I have:


while ($query->fetch()) {
	for ($i = 0; $i < count($columnNames); $i++ ) {
		
	$pagelisting[] = array($columnNames[$i] => db_connection::get_column($columnNames[$i]));
					
	}
}

that generates this:


Array
(
    [0] => Array
        (
            [name] => home
        )

    [1] => Array
        (
            [id] => 1
        )

    [2] => Array
        (
            [name] => About
        )

    [3] => Array
        (
            [id] => 2
        )

)

I don’t want the name and id to be separated into a new array each time. I tried using array_splice but it didn’t quite get the right result, or maybe it can?

Most extensions and libraries that work with databases have functionality to fetch an entire row as an array. I’d be really surprised if yours didn’t. We can’t tell what you’re using from the code you posted.

Hey crmalibu, thanks for replying. Part of the problem is I wrote my own database class using prepared statements (for the security benefit). There’s no fetch_array method for prepared statments, so I adopted the code on this page: Scroll down to second comment to see the code. I implimented that, but only got the Get($column_name) method working. So it’s 1 result at a time.

If that’s too vague I’ll post the entire database class.


while ($query->fetch()) {

	$row = array();
	$pagelisting[] =& $row;

    for ($i = 0; $i < count($columnNames); $i++ ) {
    	
    	$row[$columnNames[$i]] = db_connection::get_column($columnNames[$i]);
                    
    }
    
} 

Thanks oddz! Using the reference only returned the last result three times, but with slight modifications it works great.


while ($query->fetch()) {

	$row = array();
				
		for ($i = 0; $i < count($columnNames); $i++ ) {
				    
			 $row[$columnNames[$i]] = db_connection::get_column($columnNames[$i]);
						
		}

	$pagelisting[] = $row;
}

ouputs:


Array
(
    [0] => Array
        (
            [name] => home
            [id] => 1
        )

    [1] => Array
        (
            [name] => About
            [id] => 2
        )

    [2] => Array
        (
            [name] => contact
            [id] => 3
        )

)


Case closed :slight_smile: