Reputation: 27
I am Having trouble in fetching data from json array in laravel.I have json array and i want to show data under two different select option but i dont know how to fetch after json_decode() not using jquery just in php..!!
{
"option":["Size","Color"],
"values":["L|M|S","Red|Green|Black"],
"price":["9000|8000|6000","9000|8000|6000"]
}
I want to display it under these select options like color under color select option and size under size select option in laravel blade..!!
Upvotes: 1
Views: 1552
Reputation: 1494
You must first decode the JSON string and then use a @foreach to make the select box. Although I don't know what are you trying to do because the values of select box options are important to know which price belongs to which. But here is the code you want:
@php
$js = '{
"option":["Size","Color"],
"values":["L|M|S","Red|Green|Black"],
"price":["9000|8000|6000","9000|8000|6000"]
}';
$js = json_decode($js);
@endphp
@foreach($js->option as $index => $option)
<select name="{{$option}}" id="{{$option}}">
@php
$values = $js->values[$index];
$values = explode('|',$values);
$prices = $js->price[$index];
$prices = explode('|',$prices);
@endphp
<option disabled selected>{{$option}}</option>
@foreach($values as $indx => $value)
<option value="{{$prices[$indx]}}">{{$value}} {{$prices[$indx]}}$</option>
@endforeach
</select>
@endforeach
Usually, you must send a product object to view and then use the properties of the object here. Then you must add the id of product in the value of options. To detect what is the product that the user trying to buy.
Upvotes: 2
Reputation: 184
Create Halper method for this.
$jsonString = '{
"option":["Size","Color"],
"values":["L|M|S","Red|Green|Black"],
"price":["9000|8000|6000","9000|8000|6000"]
}';
print_r(createItemAttributes($jsonString, $valueSpliter = '|'));
function createItemAttributes($jsonString, $valueSpliter = '|'){
$itemAttributes = json_decode($jsonString);
$options = [];
foreach($itemAttributes->option as $key => $value){
$options[$value] = explode('|',$itemAttributes->values[$key]);
}
$html = [];
foreach($options as $option => $values ){
$selectStart = '<select name="'.$option.'">';
$selectEnd = '</select>';
$valueString = '';
foreach($values as $value){
$valueString .= '<option value="'.$value.'">'.$value.'</option>';
}
$html[$option] = $selectStart.$valueString.$selectEnd;
}
return $html;
}
?>
Upvotes: 0