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?

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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>";

Comments

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

Comments

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
        )

)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.