php 将数组和数组中的对象转换为纯数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10631767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting array and objects in array to pure array
提问by Thompson
My array is like:
我的数组是这样的:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => demo1
)
[1] => stdClass Object
(
[id] => 2
[name] => demo2
)
[2] => stdClass Object
(
[id] => 6
[name] => otherdemo
)
)
How can I convert the whole array (including objects) to a pure multi-dimensional array?
如何将整个数组(包括对象)转换为纯多维数组?
回答by Ibrahim Azhar Armar
Have you tried typecasting?
你试过打字吗?
$array = (array) $object;
There is another trick actually
其实还有一个技巧
$json = json_encode($object);
$array = json_decode($json, true);
You can have more info here json_decodein the PHP manual, the second parameter is called assoc:
您可以json_decode在 PHP 手册中获得更多信息,第二个参数称为assoc:
assoc
When
TRUE, returned objects will be converted into associative arrays.
协会
当 时
TRUE,返回的对象将被转换为关联数组。
Which is exactly what you're looking for.
这正是您要寻找的。
You may want to try this, too : Convert Object To Array With PHP (phpro.org)
回答by Mahdi Shad
Just use this :
只需使用这个:
json_decode(json_encode($yourArray), true);
回答by Baba
You can use array_walkto convert every item from object to array:
您可以使用array_walk将每个项目从对象转换为数组:
function convert(&$item , $key)
{
$item = (array) $item ;
}
array_walk($array, 'convert');
回答by Ade
Assuming you want to get to this pure array format:
假设您想使用这种纯数组格式:
Array
(
[1] => "demo1",
[2] => "demo2",
[6] => "otherdemo",
)
Then I would do:
然后我会这样做:
$result = array();
foreach ($array as $object)
{
$result[$object->id] = $object->name
}
(edit) Actually that's what I was looking for possibly not what the OP was looking for. May be useful to other searchers.
(编辑)实际上这就是我正在寻找的可能不是 OP 正在寻找的。可能对其他搜索者有用。
回答by magnetik
You should cast all objets, something like :
您应该投射所有对象,例如:
$result = array();
foreach ($array as $object)
{
$result[] = (array) $object
}
回答by David Barker
As you are using OOP, the simplest method would be to pull the code to convert itself into an array to the class itself, you then simply call this method and have the returned array populate your original array.
当您使用 OOP 时,最简单的方法是提取代码以将其自身转换为类本身的数组,然后您只需调用此方法并让返回的数组填充您的原始数组。
class MyObject {
private $myVar;
private $myInt;
public function getVarsAsArray() {
// Return the objects variables in any structure you need
return array($this->myVar,$this->myInt);
}
public function getAnonVars() {
// If you don't know the variables
return get_object_vars($this);
}
}
See: http://www.php.net/manual/en/function.get-object-vars.phpfor info on get_object_vars()
有关信息,请参见:http: //www.php.net/manual/en/function.get-object-vars.phpget_object_vars()

