-3

object(stdClass)#323 (3) { ["content"]=> string(157) "{"message":"Could not create contact.{"name":["The name field is required."],"mobile_number":["The mobile number field is required."]}","status":422}" ["status"]=> int(422) ["contentType"]=> string(16) "application/json" }

another response is

object(stdClass)#323 (3) { ["content"]=> string(333) "{"data":{"accounts_id":922,"virtual_account":"xxxxxxxx"},"status":200}" ["status"]=> int(200) ["contentType"]=> string(16) "application/json" }

How do i extract array attached with 'message' and data in php?

ANOL GHOSH
  • 63
  • 1
  • 7
  • Jonnix How do i extract ""{"message":"Could not create contact.{"name":" ; "name " which is connected with a string Of message object; i tried a lot of thing not working ; you have any solution ? – ANOL GHOSH Oct 22 '20 at 10:28

1 Answers1

0

This isn't an array, as you can see from the var_dump its an object (stdClass) so you access an object in PHP by doing $object->property, in your case there is a string inside your object which is json that needs to be decoded before using as a array.

You need to do the following

$message = json_decode($object->content);

This would give you $message as an object, to get the content as an array you need to add true as the second parameter of json_decode

$message = json_decode($object->content, true);

See: https://www.php.net/manual/en/function.json-decode.php

Josh Bonnick
  • 1,459
  • 1
  • 5
  • 20
  • In this case this will deliver "{"message":"Could not create contact.{"name":["The name field is required."],..... How do i separate "Could not create contact." and .{"name":["The name field is required."] ??? – ANOL GHOSH Oct 22 '20 at 10:32
  • @ANOLGHOSH Please read the links that have been provided to you. They explain in detail how to extract the data. – Jonnix Oct 22 '20 at 10:33
  • Here is the Code $response = Curl::to($url) ->withBearer($bearer) ->withData($arrey) ->returnResponseObject() ->post(); request()->session()->flash('success', $response->content['data']); return back(); – ANOL GHOSH Oct 22 '20 at 10:34
  • You need to use `json_decode` so... ill do it for you... `flash('success', json_decode($response->content, true)['data'])` – Josh Bonnick Oct 22 '20 at 10:35
  • @Josh json_decode($response->content, true)['message'] == string(122) "Could not create contact.{"name":["The name field is required."],"mobile_number":["The mobile number field is required."]}" Now How do i separate "Could not create contact and {"name":["The name field is required."]; it doesnt look like a array in any way it is array is concatenated with DOT. – ANOL GHOSH Oct 22 '20 at 10:56
  • You could just remove the `Could not create contact.` from the string and then `json_decode` it. But this is poor design on behalf of the API your using. Returning text and json in the same value doesn't make sense. – Josh Bonnick Oct 22 '20 at 11:35