从数组中删除stdClass对象

时间:2013-05-07 13:32:44

标签: php

我有一个像下面的数组(数组1),我需要从它中删除stdClass,如下面的数组no。 2.目前我正在使用foreach循环,有没有更好的方法来做循环?

阵列号

array(3) {
  [0] => object(stdClass)#169 (4) {
    ["id"] => string(2) "59"
    ["name"] => string(13) "test"
    ["email"] => string(21) "abc@abc.com"
    ["telephone"] => string(20) "898998989"
  }
  [1] => object(stdClass)#190 (4) {
    ["id"] => string(2) "58"
    ["name"] => string(13) "test"
    ["email"] => string(21) "abc@abc.com"
    ["telephone"] => string(8) "71877858"
  }
  [2] => object(stdClass)#193 (4) {
    ["id"] => string(2) "34"
    ["name"] => string(9) "test"
    ["email"] => string(22) "abc@abc.com"
    ["telephone"] => string(13) "3189028092139"
  }
}

数组2

array(3) {
  [0] => array(4) {
    ["id"] => string(2) "62"
    ["name"] => string(5) "test"
    ["email"] => string(22) "abc@abc.com"
    ["telephone"] => string(10) "898998989"
  }
  [1] => array(4) {
    ["id"] => string(2) "59"
    ["name"] => string(13) "test"
    ["email"] => string(21) "abc@abc.com"
    ["telephone"] => string(20) "71877858"
  }
  [2] => array(4) {
    ["id"] => string(2) "58"
    ["name"] => string(13) "test"
    ["email"] => string(21) "abc@abc.com"
    ["telephone"] => string(8) "3189028092139"
  }
}

这就是我所做的(演员)

foreach($moderationContacts as $contact)
{
    $contacts[] = (array)$contact;
}

2 个答案:

答案 0 :(得分:7)

尝试

$array = json_decode( json_encode($array), true);

编辑: 我已经测试了这个案例,它的确有效:

$stdClass= new stdClass();
$stdClass->test = "foo";
$array = Array(
    "a" => Array("b","c"),
    "d" => $stdClass
);

$array = json_decode( json_encode($array), true);

var_dump($array);

输出

array
  'a' => 
    array
      0 => string 'b' (length=1)
      1 => string 'c' (length=1)
  'd' => 
    array
      'test' => string 'foo' (length=3)

答案 1 :(得分:2)

你可以尝试

$array = array_map(function ($v) {
    return (array) $v ; // convert to array 
}, $array);

或者,如果此数据来自json使用

$array = json_decode($data,true);