I saved the result of a CURL expression into variable $data. When I print this value using print_r($data), It gives me like that
stdClass Object
(
[zip_codes] => Array
(
[0] => stdClass Object
(
[zip_code] => 10015
[distance] => 0.521
)
[1] => stdClass Object
(
[zip_code] => 10079
[distance] => 0.521
)
[2] => stdClass Object
(
[zip_code] => 10094
[distance] => 0.521
)
I want only zip_code into an array, Please help me how do I get only zip_code into an array. Thanks
Try something like :
foreach($data->zip_codes as $zipObj)
{
echo $zipObj->zip_code;
}
This will loop over the zip codes array and output the relevant value.
So use array_map()
:
$result = array_map(function($x)
{
return $x->zip_code
}, $obj->zip_codes);
Try something like this: First iterate trought the collection of objects an get the zip code property and add it to an array
<?php
$result = array();
$zipCodes = $data->zip_codes;
for($i = 0; $i < sizeOf($zipCodes); $i++){
$result[] = $zipCodes->zip_code;
}
?>
You can use array_map, this function allows you to apply a callback to the array.
$zip_codes = array_map(function($i) { return $i->zip_code; }, $data->zip_codes);