Search code examples
phpjson

How add IF in PHP and for checking use data from API then do foreach data


I want do IF in PHP which getting data from API and compares this data with data in PHP variables and if it same data then doing foreach for the data details not for all of the data from API.

JSON:

{"10":{"name":"Cassius Mcbride"},"20":{"name":"Lena Walton"}}';

PHP:

<?php
$curl_handle = curl_init();
$api_url = 'urlToAPI';
curl_setopt($curl_handle, CURLOPT_URL, $api_url);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
$curl_data = curl_exec($curl_handle);
curl_close($curl_handle);
$response_data = json_decode($curl_data, true);
$user_data = $response_data;
$test = 10;
if($user_data->$data == $test) //ye I know it's don't have right working but I don't know how otherwise show what I mean
{
    foreach ($user_data as $data=>$data_detals )
    {
        echo "<br />";
        echo "id: ".$data;
        echo "<br />";
        echo "name: ".$data_detals['name'];
        echo "<br />";
        echo "<br />";
    }
}

?>

I did something like this:

$test = 10;

foreach ($user_data as $data=>$data_detals )
{
    if($data == $test)
    {
            echo "<br />";
            echo "id: ".$data;
            echo "<br />";
            echo "name: ".$data_detals['name'];
            echo "<br />";
            echo "<br />";
    }
}

It's worked of course, but I thinking how I can do do it in other way that be don't use foreach for all data but only for details, and $data (id) checking in using something else way for using less power for this. I want skip foreach for other registers. This is possible?


Solution

  • If you want to only get that key (10), you can do it like this :

    $test = 10;    
    $user_data = $response_data[$test];
    

    here is an example of getting the name.