Convert an associate array to an object?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Robert Oschler

    Convert an associate array to an object?

    With PHP 4, is there a way to convert an associative array to an object?

    For example, suppose I have the following arrays inside a nested associative
    array ($nestedAA):

    $AA1['field1'] = 'fieldValue1';

    $AA2['field2'] = 'fieldValue2';

    $nestedAA['AA1'] = $AA1;
    $nestedAA['AA2'] = $AA2;

    I would like to take $nestedAA and convert it to an object called
    $nestedObject with properties I could access like this:

    echo $nestedObject->AA1->field1; # This would print 'fieldValue1'
    echo $nestedObject->AA2->field2; # This would print 'fieldValue2'

    How can I do this? Note, I would like a conversion method that I could use
    with any nested associativee array and create the object dynamically (at
    runtime).

    Thanks,
    Robert




  • Andy Hassall

    #2
    Re: Convert an associate array to an object?

    On Thu, 9 Jun 2005 12:59:12 -0400, "Robert Oschler" <no-mail-please@nospam.c om>
    wrote:
    [color=blue]
    >With PHP 4, is there a way to convert an associative array to an object?
    >
    >For example, suppose I have the following arrays inside a nested associative
    >array ($nestedAA):
    >
    >$AA1['field1'] = 'fieldValue1';
    >
    >$AA2['field2'] = 'fieldValue2';
    >
    >$nestedAA['AA1'] = $AA1;
    >$nestedAA['AA2'] = $AA2;
    >
    >I would like to take $nestedAA and convert it to an object called
    >$nestedObjec t with properties I could access like this:
    >
    >echo $nestedObject->AA1->field1; # This would print 'fieldValue1'
    >echo $nestedObject->AA2->field2; # This would print 'fieldValue2'
    >
    >How can I do this? Note, I would like a conversion method that I could use
    >with any nested associativee array and create the object dynamically (at
    >runtime).[/color]

    Something like:

    <pre>
    <?php
    $AA1['field1'] = 'fieldValue1';
    $AA2['field2'] = 'fieldValue2';

    $nestedAA['AA1'] = $AA1;
    $nestedAA['AA2'] = $AA2;

    var_dump($neste dAA);

    function array_to_obj($a rray, &$obj)
    {
    foreach ($array as $key => $value)
    {
    if (is_array($valu e))
    {
    $obj->$key = new stdClass();
    array_to_obj($v alue, $obj->$key);
    }
    else
    {
    $obj->$key = $value;
    }
    }
    return $obj;
    }

    $nestedObject= new stdClass();
    array_to_obj($n estedAA, $nestedObject);

    print_r($nested Object);

    echo $nestedObject->AA1->field1; # This would print 'fieldValue1'
    echo $nestedObject->AA2->field2; # This would print 'fieldValue2'

    ?>
    </pre>

    --
    Andy Hassall / <andy@andyh.co. uk> / <http://www.andyh.co.uk >
    <http://www.andyhsoftwa re.co.uk/space> Space: disk usage analysis tool

    Comment

    Working...