Doubt how to manipulate (delete attribute) an Object or Json in php

Asked

Viewed 48 times

0

The idea of the application is to create a json template from the string

The string is always changed but respecting the syntax that is like accessing the elements and an object $var; from the following string:

$var->abreviacao
$var->array[0]->nome
$var->array[0]->idade
$var->id
$var->sala

I want to turn into a json with the following structure:

{
    "abreviacao":"none",
    "array":[
        {
            "nome":"none",
            "idade":"none",
        }
    ]
    "sala":"none",
    "id":"none"
}

Note: The object $var not only exists the string exists

I thought about building an object and adding attributes with Eval() however when creating an object as follows

$obj = (object) 'string aleatoria';
$obj->array[0]->nome="none";
$obj->array[0]->idade="none";
$obj->sala="none";
$obj->id="none";
echo json_encode($obj);

an unwanted attribute is created

$var->scalar

Need or delete an attribute from json or object either of the two would serve

  • Read: https://www.devmedia.com.br/trabando-com-json-em-php/26716

  • Tried to create the object as $obj = new stdClass();? Thus the attribute scalar is not created. Anyway, it wasn’t very clear to me, you get a string with the code ($obj->array etc...)?

  • That’s right I get a string with if I was accessing an object attribute. !

1 answer

0

did as hkotsubo referred me.

To create the object I used:

$obj = new stdClass();

instead of:

$obj = (object) 'string aleatoria';`

Thus the scalar attribute is not created.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.