Antonis
Antonis

Reputation: 195

How to display some of the JSON Data in select option using php?

I connect to an API and receive a JSON Data with PHP. After execute:

$countries= curl_exec($ch);
$jd_countries = json_decode($countries, TRUE);
print $countries;

The result of this is:

enter image description here

I would like to use for each to add the country_id and name to option value

So my code will be something like this:

<select name="country" class="form-control" >
    <?php foreach($jd_countries as $value){ ?>
        <option value="<?php echo $country_id;?>"><?php echo $name;?>
        </option> 
    <?php } ?>
</select>

I receive this:

Notice: Array to string conversion in C:\xampp\htdocs\account\index.php on line 28 Array

Notice: Array to string conversion in C:\xampp\htdocs\account\index.php on line 28 Array

Any suggestions? Thanks in advance.

Upvotes: 0

Views: 787

Answers (2)

Denis
Denis

Reputation: 410

<?php foreach($jd_countries['data'] as $country){ ?>
   <option value="<?php echo $country['country_id'];?>"><?php echo $country['name'];?>
   </option>
<?php } ?> 

Upvotes: 3

Somnath Rokade
Somnath Rokade

Reputation: 665

You need to convert $countries to array

$jd_countries= json_decode($countries, TRUE);

<?php foreach($jd_countries->data as $country){ ?>
   <option value="<?php echo $country['country_id'];?>"><?php echo $country['name'];?>
   </option>
<?php } ?> 

Upvotes: 0

Related Questions