[英]how to convert the stdobject array into normal array
Array
(
[0] => stdClass Object
(
[card] => stdClass Object
(
[name] => Abc
[number] => 1234567123456798
[exp_month] => 1
[exp_year] => 2015
[cvc] => 123
)
[deliveryPeriod] => stdClass Object
(
[id] => 1
[store_id] => 1
[start_date] => 2014-11-01
[end_date] => 2014-12-31
[delivery_schedules] => Array
(
[0] => stdClass Object
(
[id] => 1
[delivery_period_id] => 1
[start_time] => 09:00:00
[end_time] => 18:00:00
[slot_capacity] => 25
[delivery_fee] => 2
[used_capacity] => 1
)
)
)
)
)
)
I have this stdclass object array and i want to convert this to a normal array.I was using foreach but i can loop through inner array.how can i do that in php.please help me i am new to php. 我有这个stdclass对象数组,我想将其转换为普通array。我正在使用foreach,但是我可以循环遍历内部array。如何在php中做到这一点,请帮助我我是php的新手。
Use json_decode() and json_encode() 使用json_decode()和json_encode()
$array = json_decode(json_encode($object), true);
Where $object
is your multi-dimensional nested object. 其中
$object
是您的多维嵌套对象。
Explanation: 说明:
First JSON encode your object, then JSON decode it. 首先,JSON对您的对象进行编码,然后对它进行JSON解码。
With second argument associative
to TRUE
. 第二个参数
associative
TRUE
associative
。
This way, you will get an associative array without caring of nested depth. 这样,您将获得一个关联数组,而无需关心嵌套深度。
Create a recursive function 创建一个递归函数
function objectToArray($obj, &$new_array){
foreach($obj as $key => $value){
if(is_object($value){
$new_array[$key] = array();
objectToArray($value, $new_array[$key]);
} else {
$new_array[$key] = $value;
}
return $new_array;
}
}
You can just use typecasting by using (array)
in front of the array in question... So for you: 您可以通过在有问题的数组前面使用
(array)
来使用类型转换...因此,对于您来说:
foreach($array as $item) {
$itemArray = (array)$item;
}
You could typecast your array like the example below: 您可以像下面的示例一样对数组进行类型转换:
<?php
$obj = new stdClass();
$obj->test = 'Hello';
var_dump($obj);
$arr = (array)$obj;
var_dump($arr);
Returns: 返回值:
object(stdClass)#1 (1) {
["test"]=>
string(5) "Hello"
}
array(1) {
["test"]=>
string(5) "Hello"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.