0

How to assign array elements as object properties in PHP

$arr_zone_area = [];
foreach ($area as $key_area=>$row_area)
{
    foreach ($nominalRoll as $key => $value)
    {
        if ($row_area->ADMIN_ID == $value->AREA_ID)
        {
            $arr_zone_area[$key_area]['ZONE_NAME'] = $row_area->ZONE_NAME;
            $arr_zone_area[$key_area]['AREA_NAME'] = $row_area->AREA_NAME;
        }
    }
}

Output:

(
    [0] => Array
        (
            [ZONE_NAME] => Dhaka
            [ADMIN_ID] => Admin Dhaka
        )

)

I want the output like this

(
    [0] => stdClass Object
        (
            [ZONE_NAME] => Dhaka
            [ADMIN_ID] => Admin Dhaka
        )

)

Can anyone help me?

Thanks in advance

0

2 Answers 2

2

Just cast the values to an object when you assign them in the loop:

$arr_zone_area[$key_area] = (object)['ZONE_NAME' => $row_area->ZONE_NAME,
                                     'AREA_NAME' => $row_area->AREA_NAME
                                    ];
Sign up to request clarification or add additional context in comments.

Comments

1

you can use JSON encode and then decode it back, you will get the object. Something like this.

$obj_zone_area = json_decode(json_encode($arr_zone_area ));

now $obj_zone_area is a object.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.