0

I have an array with sub-array:

$test = array("hello" => "world", "object" => array("bye" => "world"));

I want to convert it to object:

$obj = (object) $test;

The parent array becomes object, but child is still array:

object(stdClass)[1]
  public 'hello' => string 'world' (length=5)
  public 'object' => 
    array (size=1)
      'bye' => string 'world' (length=5)

But I want to get something like this:

object(stdClass)[1]
  public 'hello' => string 'world' (length=5)
  public 'object' => 
    object(stdClass)[2]
      public 'bye' => string 'world' (length=5)

This could be reached with this code:

$testObj = json_decode(json_encode($test));

But it's bad practice. How can I reach this result?

artem
  • 16,382
  • 34
  • 113
  • 189

5 Answers5

3

Try This may help.

how to convert multidimensional array to object in php?

function convert_array_to_obj_recursive($a) {
if (is_array($a) ) {
    foreach($a as $k => $v) {
        if (is_integer($k)) {
            // only need this if you want to keep the array indexes separate
            // from the object notation: eg. $o->{1}
            $a['index'][$k] = convert_array_to_obj_recursive($v);
        }
        else {
            $a[$k] = convert_array_to_obj_recursive($v);
        }
    }

    return (object) $a;
}

// else maintain the type of $a
return $a; 
}

Let me know if it worked.

Community
  • 1
  • 1
Nikhil Joshi
  • 386
  • 2
  • 18
1

Try this:

function cast($array) {
    if (!is_array($array)) return $array;
    foreach ($array as &$v) {
        $v = cast($v);
    }
    return (object) $array;
}
$result = cast($test);

Demo

hindmost
  • 7,125
  • 3
  • 27
  • 39
1

You can do this using this way, via a foreach and conditions:

$array = array("hello" => "world", "object" => array("bye" => "world"));

foreach($array as $key => $val) {

    if(is_array($val)) {
        $aa[$key] = (object) $val; 
    }
    else {
        $aa[$key] = $val;
    }

    $obj  = (object) $aa;
}

echo "<pre>";
var_dump($obj);
echo "</pre>";
fortune
  • 3,361
  • 1
  • 20
  • 30
0

I think you are looking for this

$object = new stdClass();
foreach ($array as $key => $value)
{
    $object->$key = $value;
}

and use in built in json $object = json_decode(json_encode($array), FALSE);..It converts all your sub arrays into objects..

If this is not the answer you are expecting please comment below

Avinash Babu
  • 6,171
  • 3
  • 21
  • 26
0
function arrayToObject($arr) {
    if (is_array($arr)) 
        return (object) array_map(__FUNCTION__, $arr);

    else
        return $arr;
}

The output of arrayToObject($test) would then be,

stdClass Object
(
    [hello] => world
    [object] => stdClass Object
        (
            [bye] => world
        )

)
Erlesand
  • 1,525
  • 12
  • 16