Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove stdClass objects from array

Tags:

php

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;
}
like image 664
Shaolin Avatar asked Dec 20 '22 06:12

Shaolin


1 Answers

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)
like image 56
Luca Rainone Avatar answered Jan 04 '23 09:01

Luca Rainone