Those data in $data variable. When I'm using dd($data); I got this:
CurlHandle {#1918 ▼
url: "https://example.com"
content_type: "application/json; charset=UTF-8"
http_code: 200
header_size: 887
namelookup_time_us: 139522
pretransfer_time_us: 326662
redirect_time_us: 0
starttransfer_time_us: 668686
total_time_us: 668752
}
I want to convert this data to an array.
I'm using this: $arr = json_decode($data,true);
But, this is not working. Now, how can I convert this?
CodePudding user response:
while this is a PHP Object so you can deal with it by 2 ways:
1- if you want to get on of it's parameters, you can simply use
$yourObject->parameter;
2- if you need to use convert and use it as array, then there is different ways to convert an object to an array in PHP
//1
$array = (array) $yourObject;
//2
$array = json_decode(json_encode($yourObject), true);
Also see this in-depth blog post:
Fast PHP Object to Array conversion
CodePudding user response:
You can use below solution
$yourArray = json_decode(json_encode($yourObject), true);
and this convert object to an array for more info
CodePudding user response:
Objects are, in PHP, maybe iterable. Notice, you may iterate through an object's public fields only via the foreach loop. So the following works:
$array = [];
foreach ($object as $property) {
$array[] = $property; // Stores public field only
}
var_dump($array);
Simply to get an array of object properties, you may use the get_object_vars() function.
var_dump(get_object_vars($object));
You may cast an object to be an array as @MoussabKbeisy said. And this would be the easiest way:
$array = (array) $object;
Here is another way is using ArrayIterator:
$iterator = new ArrayIterator($object);
var_dump(iterator_to_array($iterator));
