Reputation: 3925
I have a ecommerce-web, In my controller I have a code that controls a list of countries that are displayed in the cart.
If the price of the country where we are is greater than or equal to the price of shipping to other countries, these countries are added to the list:
This is my controller code:
$params['final_countries_list'] = [];
$list_countries = Config::get('app.web_config.shipment.countries');
$base_price = $list_countries[Config::get('app.web_country')]['price'];
foreach($list_countries as $key=>$value) {
if ($value['price'] <= $base_price)
$params['final_countries_list'][$key] = $value;
}
Well, if I do a dd($params['final_countries_list']), I get this result.
array(13) {
["deu"] array(2) {
["name"] "Deutschland"
["price"] 9
}
["che"] array(2) {
["name"] "Schweiz"
["price"] 9
}
["fra"] array(2) {
["name"] "France"
["price"] 8
}
["gbr"] array(2) {
["name"] "United Kingdom"
["price"] 9
}
ETC,ETC...
Now I want to get this(deu, fra, gbr, etc) in view cart.blade.php
In the cart.blade.php have this code to get what I want:
<select name="country" id="pais">
<option value="" selected><--- Choose Country ---></option>
<?php foreach($final_countries_list as $key => $value){?>
<option value="<?php echo $key?>"><?php echo $value. ' ('.$key.')';?></option>
<?php } ?>
</select>
And I get the following error:
ErrorException (E_UNKNOWN) Array to string conversion (View: C:\xampp\htdocs\my_web_name\app\views\cart.blade.php)
How I can fix it?
Upvotes: 0
Views: 13761
Reputation: 664
You should use $country['name']
P.S.
If You are using blade you can simplify your code by using blade helper shortcodes
(e.g. @foreach
).
With this in mind you can rewrite your code simpler
<select name="country">
<option value="" selected>Select your county</option>
@foreach($final_countries_list as $key => $country)
<option value ="{{ $key }}">{{ $country['name'] }} ({{ $key }})</option>
@endforeach
</select>
Upvotes: 3
Reputation: 152900
The simplest way would just be to don't assign the full value but only the name
: (If you don't need the price in the view)
foreach($list_countries as $key=>$value) {
if ($value['price'] <= $base_price)
$params['final_countries_list'][$key] = $value['name'];
}
An a bit nicer (in my opinion)
$list_countries = array_filter($list_countries, function($value){
return $value['price'] <= $base_price
});
$params['final_countries_list'] = array_map(function($value){
return $value['name'];
}, $list_countries);
Upvotes: 4
Reputation: 24661
The issue is that you are iterating over an array of arrays, but the sub-array you are treating as if it were a string (why you're getting the error). If I understand you correctly, a simple change can get you what you want:
<option value="<?php echo $key?>"><?php echo $value['name']. ' ('.$key.')';?></option>
Upvotes: 1