Converting a particular array to an object
I'm looking for an elegant approach to co开发者_开发知识库nvert $array
to $object
.
If $array
contains Array ( [0] => en=english [1] => fr=french )
the resulting $object
should contain stdClass Object ( [en] => english [fr] => french )
The most elegant approach would be the one that uses the least variable names.
Should do it:
$object = new stdClass();
$array = array('en=english','fr=french', 'foo=bar=baz');
foreach($array as $item){
list($name, $value) = explode('=', $item, 2);
$object->$name = $value;
}
You could also use parse_ini_string
$object = (object) parse_ini_string(join(PHP_EOL, $array));
As long as all your values are key=val
this will work.
All rules for ini files apply, meaning it will choke on foo=bar=baz
but not on foo="bar=baz"
because ini files allow additional =
when it's put into quotes.
If you are not on PHP 5.3 yet, you can use parse_ini_file
to accept the joined array contents from a data stream wrapper. This requires allow_url_include
to be enabled in your php.ini though.
$object = (object) parse_ini_file(
'data:text/plain,' . urlencode(join(PHP_EOL, $array))
);
In both cases, the output is the same.
Best way to do this:
<?php
$arr = array('en=english','test=blaat','foo=bar=test');
foreach ($arr as $item)
{
$opts = explode('=',$item);
$name = array_shift($opts);
$obj->$name = implode('=',$opts);
}
print_r($obj);
Returns:
stdClass Object
(
[en] => english
[test] => blaat
[foo] => bar=test
)
You could do this
foreach ($arr as $item)
{
$things=explode('=',$item);
$newArray[$things[0]]=$things[1];
}
$obj=(object) $newArray;
精彩评论