Get specific values from CURL JSON response php array

Viewed 10460

Trying to echo a couple of values from the CURL JSON response so i can put them in to a foreach loop but i can only get single indexed values to work.

$request = curl_init($api); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/x-www-form-urlencoded"
));

$response = (string)curl_exec($request); // execute curl fetch and store results in $response

curl_close($request); // close curl object

$result = json_decode($response, true); // true turns it into an array
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
echo 'Last Name: ' . $result[0]['last_name'] . '<br />'; // yet i can return the first value

Example Array output

Array
(
    [0] => Array
        (
            [id] => 34761
            [first_name] => A
            [last_name] => Bailes
            [clinic] => 
            [phone] => 7409923279
            [fax] => 7409926740
            [address1] => 507 Mulberry Heights Rd
            [address2] => 
            [city] => Pomeroy
            [subdivision] => OH
            [country_code] => 
            [postal_code] => 45769-9573
            [timezone] => Array
                (
                    [timezone_type] => 3
                    [timezone] => America/New_York
                )

            [state] => OH
        )
)

I have json decode set to true for array output

$result = json_decode($response, true); // true turns it into an array

but when i try to echo the 'first_name' values it just returns empty.

echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work

Yet i can return an indexed value

echo 'First Name: ' . $result[0]['first_name'] . '<br />';

What am i doing wrong here?

1 Answers
Related