0

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.

1
  • What is $jd_countries ? And you never use $value, what is $country_id and $name ? Commented Jul 24, 2019 at 9:27

2 Answers 2

3
<?php foreach($jd_countries['data'] as $country){ ?>
   <option value="<?php echo $country['country_id'];?>"><?php echo $country['name'];?>
   </option>
<?php } ?> 
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Denis. Thanks for your answer. I change my code and I receive this error: Notice: Trying to get property of non-object in C:\xampp\htdocs\account\index.php on line 27 Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\account\index.php on line 27
hey yes, sorry I was trying to take the data like $jd_countries->data but it's an array not object so change it to $jd_countries['data']. I also have changed the answer
0

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 } ?> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.