如何从laravel中的json数组中获取数据

我在从 Laravel 中的 json 数组获取数据时遇到问题。我有 json 数组,我想在两个不同的选择选项下显示数据,但我不知道如何在 json_decode() 之后获取数据,而不是在 php 中使用 jquery ..!!


{

"option":["Size","Color"],

"values":["L|M|S","Red|Green|Black"],

"price":["9000|8000|6000","9000|8000|6000"]

}

我想在这些选择选项下显示它,例如 Laravel Blade 中的颜色选择选项和尺寸下的尺寸选择选项......!!


慕码人8056858
浏览 361回答 2
2回答

BIG阳

您必须首先解码 JSON 字符串,然后使用 @foreach 来制作选择框。虽然我不知道你想做什么,因为选择框选项的值对于知道哪个价格属于哪个很重要。但这是您想要的代码:&nbsp; &nbsp; @php&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;$js = '{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "option":["Size","Color"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "values":["L|M|S","Red|Green|Black"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "price":["9000|8000|6000","9000|8000|6000"]&nbsp; &nbsp; &nbsp; &nbsp;}';&nbsp; &nbsp; &nbsp; &nbsp;$js = json_decode($js);&nbsp; &nbsp; @endphp@foreach($js->option as $index => $option)&nbsp; &nbsp; <select name="{{$option}}" id="{{$option}}">&nbsp; &nbsp; &nbsp; &nbsp; @php&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $values = $js->values[$index];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $values = explode('|',$values);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $prices = $js->price[$index];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $prices = explode('|',$prices);&nbsp; &nbsp; &nbsp; &nbsp; @endphp&nbsp; &nbsp; &nbsp; &nbsp; <option disabled selected>{{$option}}</option>&nbsp; &nbsp; &nbsp; &nbsp; @foreach($values as $indx => $value)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="{{$prices[$indx]}}">{{$value}} {{$prices[$indx]}}$</option>&nbsp; &nbsp; &nbsp; &nbsp; @endforeach&nbsp; &nbsp; </select>@endforeach通常,您必须发送一个产品对象来查看,然后在此处使用该对象的属性。然后您必须在选项的值中添加产品的 id。检测用户尝试购买的产品是什么。

慕少森

为此创建 Halper 方法。$jsonString = '{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "option":["Size","Color"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "values":["L|M|S","Red|Green|Black"],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "price":["9000|8000|6000","9000|8000|6000"]&nbsp; &nbsp; &nbsp; &nbsp;}';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]);}&nbsp; $html = [];&nbsp; foreach($options as $option => $values ){&nbsp; &nbsp; $selectStart = '<select name="'.$option.'">';&nbsp; &nbsp; $selectEnd = '</select>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $valueString = '';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach($values as $value){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $valueString .= '<option value="'.$value.'">'.$value.'</option>';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; $html[$option] = $selectStart.$valueString.$selectEnd;&nbsp; &nbsp; }&nbsp; return $html;}?>
打开App,查看更多内容
随时随地看视频慕课网APP