Welcome to the first WebLive Help Tutorial.
Today we'll give out two very useful PHP functions:
- Convert/Parse Array to Object
- Convert/Parse Object to Array
- Code: Select all
<?php
function parseArrayToObject($array) {
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = $value;
}
}
}
return $object;
}
function parseObjectToArray($object) {
$array = array();
if (is_object($object)) {
$array = get_object_vars($object);
}
return $array;
}
?>
Usage:
Convert Array $a to Object $o
- Code: Select all
<?php
$a = array (
'index_0' => 'value_0',
'index_1' => 'value_1'
);
$o = parseArrayToObject($a);
//-- Now you can use $o like this:
echo $o->index_0;//-- Will print 'value_0'
?>
Convert Object $o to Array $a
- Code: Select all
<?php
$o = new stdClass();
$o->index_0 = 'value_0';
$o->index_1 = 'value_1';
$a = parseObjectToArray($o);
//-- Now you can use $a like this:
echo $a['index_0'];//-- Will print 'value_0'
?>
Use it well!

