Hugo Sum
Hugo Sum

Reputation: 243

How to flatten this array of objects in PHP?

I have an array like this:

Array
(
    [0] => stdClass Object
        (
            [㐀] => Array
                (
                    [0] => jau1
                )

        )

    [1] => stdClass Object
        (
            [㐁] => Array
                (
                    [0] => dou6
                )

        )

    [2] => stdClass Object
        (
            [㐂] => Array
                (
                    [0] => cat1
                )

        )

)

How can I remove the stdClassObject for every element in this array?

Since the key for each element is different, I guess array_column is not going to work.

Upvotes: 2

Views: 189

Answers (2)

Rakesh Hiray
Rakesh Hiray

Reputation: 721

suppose.. $array is your main array

you can try (if you want to convert object array element to array):

$arrCnt = count($array);   
for($i=0;$i<$arrCnt;$i++) $array[$i] = (array) $array[$i];

actually you have not mentioned your query exactly. Its confusing

Or

If you want to skip stdObject from that then you can try:

$arrCnt = count($array);
$newArr = array();
for($i=0;$i<$arrCnt;$i++){ 
   $array[$i] = (array) $array[$i];   
   foreach($array[$i] as $k=>$v) $newArr[$k] = $v[0];
}
print_r();

Upvotes: 1

jeprubio
jeprubio

Reputation: 18012

you could just iterate the data and get what you want:

$res = array();
foreach ($array as $key => $val) {
    foreach ($val as $keyObj => $valObj) {
        $res[$keyObj] = $valObj[0];
    }
}

var_dump($res);

This outputs:

array(3) {
  ["㐀"]=>
  string(4) "jaul"
  ["㐁"]=>
  string(4) "dou6"
  ["㐂"]=>
  string(4) "cat1"
}

online demo

Upvotes: 4

Related Questions