Welcome Guest, Not a member yet? Register   Sign In
Setting up an array so values are called up like $a->b, instead of $a['b']
#1

[eluser]tochie[/eluser]
Hello CI brethren,

I have been wondering if its possible in CI to setup an array so the values can be called in this format
Code:
$a->b
instead of this
Code:
$a['b']

Thanks plenty
#2

[eluser]Johan André[/eluser]
Well, technically your first example is not an array. It's an object...
There are functions for converting arrays to objects... Google it! Smile
#3

[eluser]tochie[/eluser]
Thanks very much Johan for the tip. My problem was that I didn't know the $a->b was called objects. This is what i found...ror anyone that don't know this too.

Code:
<?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;
}
?>

Convert Array $a to Object $o
Code:
<?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:
<?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'
?>

Thanks.
#4

[eluser]Johan André[/eluser]
No problem! Smile
#5

[eluser]sophistry[/eluser]
be careful with that "parseArrayToObject" function. arrays and object properties are different and play by different rules.

array keys can have space characters, for instance, while object properties must abide by variable naming rules: [-_a-zA-Z0-9]+

to see what i mean, pass an array to it like this:

Code:
$a = array('valid key'=>'value1','another valid key'=>'value2');

cheers.
#6

[eluser]n0xie[/eluser]
Doesn't this just work 'out of the box'?

Code:
$myobject = (object) $myarray;




Theme © iAndrew 2016 - Forum software by © MyBB