Reputation: 2551
I have a array like below (array 1) and I need to remove stdClass from it like in below array no. 2. Currently i'm doing it using a foreach loop, is there are better way to do that wthout looping?
Array no.1
array(3) {
[0] => object(stdClass)#169 (4) {
["id"] => string(2) "59"
["name"] => string(13) "test"
["email"] => string(21) "[email protected]"
["telephone"] => string(20) "898998989"
}
[1] => object(stdClass)#190 (4) {
["id"] => string(2) "58"
["name"] => string(13) "test"
["email"] => string(21) "[email protected]"
["telephone"] => string(8) "71877858"
}
[2] => object(stdClass)#193 (4) {
["id"] => string(2) "34"
["name"] => string(9) "test"
["email"] => string(22) "[email protected]"
["telephone"] => string(13) "3189028092139"
}
}
Array no.2
array(3) {
[0] => array(4) {
["id"] => string(2) "62"
["name"] => string(5) "test"
["email"] => string(22) "[email protected]"
["telephone"] => string(10) "898998989"
}
[1] => array(4) {
["id"] => string(2) "59"
["name"] => string(13) "test"
["email"] => string(21) "[email protected]"
["telephone"] => string(20) "71877858"
}
[2] => array(4) {
["id"] => string(2) "58"
["name"] => string(13) "test"
["email"] => string(21) "[email protected]"
["telephone"] => string(8) "3189028092139"
}
}
This is what I do (casting)
foreach($moderationContacts as $contact)
{
$contacts[] = (array)$contact;
}
Upvotes: 5
Views: 26484
Reputation: 16468
try
$array = json_decode( json_encode($array), true);
EDIT: I've tested this case, and it works:
$stdClass= new stdClass();
$stdClass->test = "foo";
$array = Array(
"a" => Array("b","c"),
"d" => $stdClass
);
$array = json_decode( json_encode($array), true);
var_dump($array);
OUTPUT
array
'a' =>
array
0 => string 'b' (length=1)
1 => string 'c' (length=1)
'd' =>
array
'test' => string 'foo' (length=3)
Upvotes: 12
Reputation: 95141
You can try
$array = array_map(function ($v) {
return (array) $v ; // convert to array
}, $array);
Or if this data is from json
use
$array = json_decode($data,true);
Upvotes: 3