在保留对象名称作为键的同时将多维混合对象和数组转换为数组-PHP [英] Converting Multidimensional Mixed Object and Array to Array while Preserving Object Names as Keys - PHP
问题描述
可能重复:
将对象转换为数组
Possible Duplicate:
convert object to array
假设我有一个这样的数组:(请注意,某些方法/对象可能受到保护,因此必须在自己的类中对其进行访问)
Let's say I have an array like this: (Notice that some of the methods/objects may be protected, so they have to be accessed in their own class)
array(
0=> objectname{
[method1:protected]=> array(
["key1"] => object2{
[method2]=> array(
0 => "blah"
)
}
)
}
1=> objectname{
[method1:protected]=> array(
["key1"] => object2{
[method2]=> array(
0 => "blah"
)
}
)
}
)
我想将所有这些转换成一个数组.我通常会这样:
And I wanted to convert all of that into an Array. I would usually use this:
protected function _object_to_array($obj){
if(is_object($obj)) $obj = (array) $obj;
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = self::_object_to_array($val);
}
}else{
$new = $obj;
}
return $new;
}
问题是这不会保留对象名称.我希望对象名称成为一个额外的键,该键将数组的尺寸增大.例如,将对象名称替换为0可能有效,但更好的方法是创建这样的内容:
The problem is that this does not preserve the object names. I would like the object names to become an extra key that bumps the array up a dimension. For example, replacing the 0 for objectname could work, but better yet to create something like this:
array(
0=> array(
objectname=> array(
...blah blah
)
)
)
推荐答案
弄清楚了.
但是,新问题是,受保护的方法最终会以[* formermethodturnedkey]之类的键结尾.他们似乎无法访问.这样一个访问键怎么能?
However new problem, the protected methods endup as keys like [*formermethodturnedkey]. They don't seem to be accessible. How can one access keys like this?
protected function _object_to_array($obj){
//we want to preserve the object name to the array
//so we get the object name in case it is an object before we convert to an array (which we lose the object name)
$obj_name = false;
if(is_object($obj)){
$obj_name = get_class($obj);
$obj = (array) $obj;
}
//if obj is now an array, we do a recursion
//if obj is not, just return the value
if(is_array($obj)) {
$new = array();
//initiate the recursion
foreach($obj as $key => $val) {
//we don't want those * infront of our keys due to protected methods
$new[$key] = self::_object_to_array($val);
}
//now if the obj_name exists, then the new array was previously an object
//the new array that is produced at each stage should be prefixed with the object name
//so we construct an array to contain the new array with the key being the object name
if(!empty($obj_name)){
$new = array(
$obj_name => $new,
);
}
}else{
$new = $obj;
}
return $new;
}
这篇关于在保留对象名称作为键的同时将多维混合对象和数组转换为数组-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!