1

My API returns a JSON that I would like to transform into a PHP object so that I can find a specific field in return. how can I do this?

My get

public function teste()
{
    $requestUrl='http://XXXXXX:XXX/api/login';
    $users = array("wts-authorization: XXX/XXx","content-type: application/json","accept: application/json");
    $ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $users);
    $obj = curl_exec($ch);

}

My return

{"page":2,"per_page":6,"total":12,"total_pages":2,"data":[{"id":7,"email":"michael.lawson@reqres.in","first_name":"Michael","last_name":"Lawson","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg"},{"id":8,"email":"lindsay.ferguson@reqres.in","first_name":"Lindsay","last_name":"Ferguson","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg"},{"id":9,"email":"tobias.funke@reqres.in","first_name":"Tobias","last_name":"Funke","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/vivekprvr/128.jpg"},{"id":10,"email":"byron.fields@reqres.in","first_name":"Byron","last_name":"Fields","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/russoedu/128.jpg"},{"id":11,"email":"george.edwards@reqres.in","first_name":"George","last_name":"Edwards","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/mrmoiree/128.jpg"},{"id":12,"email":"rachel.howell@reqres.in","first_name":"Rachel","last_name":"Howell","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/hebertialmeida/128.jpg"}]}

I would like to treat as an object and use as follows

obj->first_name == "Michael"

Magento 2.3.3 Win10 Xampp

  • 1
    use json_decode funtion on that string to convert to StdClass object – Zefiryn Dec 2 '19 at 20:36
  • After running the command curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); The decoder worked Thank you! – Hudson Alves Triunfante Dec 3 '19 at 12:31
0

Solved this way

public function testeDeBanco() {

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();


    $tableName = $resource->getTableName('catalog_category_entity_varchar'); //gives table name with prefix
    $sql = "Select * FROM " . $tableName;
    $result = $connection->fetchAll($sql);
    foreach ($result as $e){
        if($e['value']=='watches'){
            echo "id:".$e['value_id'];
        }
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.