PHP Pass Dynamic Array name to function

Posted by Brad on Stack Overflow See other posts from Stack Overflow or by Brad
Published on 2012-03-29T23:02:30Z Indexed on 2012/03/29 23:29 UTC
Read the original article Hit count: 190

Filed under:
|
|

How do I pass an array key to a function to pull up the right key's data?

// The array

<?php

$var['TEST1'] = Array (
    'Description' => 'This is a Description',
    'Version' => '1.11',
    'fields' => Array(
            'ID' => array(
                    'type' => 'int',
                    'length' =>'11',
                    'misc' =>'auto_increment'
            ),
            'DATA' => array(
                    'type' => 'varchar', '
                    length' => '255'
            )
    );

$var['TEST2'] = Array (
            'Description' =? 'This is the 2nd Description',
            'Version' => '2.1',
            'fields' => Array(
                    'ID' => array(
                            'type' => 'int',
                            'length' =>'11',
                            'misc' =>'auto_increment'
                    ),
                    'DATA' => array(
                            'type' => 'varchar', '
                            length' => '255'
                    )
            )

// The function

<?php

$obj = 'TEST1';
print_r($schema[$obj]); // <-- Fives me output.  But calling the function doesn't.

echo buildStructure($obj);

/**
 * @TODO to add auto_inc support
 */

function buildStructure($obj)
{
    $output = '';
    $primaryKey = $schema["{$obj}"]['primary key'];

    foreach ($schema["{$obj}"]['fields'] as $name => $tag)
        // #### ERROR ####  Invalid argument supplied for foreach()
    {
        $type = $tag['type'];
        $length = $tag['length'];
        $default = $tag['default'];
        $description = $tag['description'];

        $length = (isset($length)) ? "({$length})" : '';
        $default = ($default == NULL ) ? "NULL" : $default;

        $output .= "`{$name}` {$type}{$length} DEFAULT {$default} COMMENT `{$DESCRIPTION}`, ";


    }
    return $output;
}

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays