如何将值拆分为数组

时间:2018-10-23 08:22:59

标签: php laravel laravel-5

如何将值拆分为数组。我有whmcs api数据,它看起来像1,2,3,4,5。我需要将值拆分为数组值,建议采取任何解决方案

我的api数据

Array
(
[result] => success
[totalresults] => 2
[promotions] => Array
    (
        [promotion] => Array
            (
                [0] => Array
                    (
                        [id] => 6
                        [code] => 0UP3NU5J7J
                        [type] => Percentage
                        [recurring] => 0
                        [value] => 15.00
                        [cycles] => One Time,Monthly,Quarterly,Semi-Annually,Annually,Biennially,Triennially,1Years
                        [appliesto] => 1,2,3
                        [requires] => 1,2,3
                        [requiresexisting] => 0
                        [startdate] => 2018-10-22
                        [expirationdate] => 2018-10-25
                        [maxuses] => 0
                        [uses] => 0
                        [lifetimepromo] => 0
                        [applyonce] => 0
                        [newsignups] => 0
                        [existingclient] => 0
                        [onceperclient] => 0
                        [recurfor] => 0
                        [upgrades] => 0
                        [upgradeconfig] => a:4:{s:5:"value";s:4:"0.00";s:4:"type";s:0:"";s:12:"discounttype";s:10:"Percentage";s:13:"configoptions";s:0:"";}
                        [notes] => 
                    )
     )
  )
)

我的代码是

   @foreach($response['promotions']['promotion'][0] as $key => $value)
     @if($key == 'appliesto')
            {{$var=$value}}
     @endif
  @endforeach

我需要将“ applyto”值拆分为一个数组。请提出任何解决方案

2 个答案:

答案 0 :(得分:2)

只需使用爆炸功能,如:

$apelistoArray = explode(',',$value);

这将返回 applyto 字段具有的值的数组,因此您需要将它们解析为数组。

在使用大括号回显刀片中的值之前,必须在循环内解析此新数组。

所以您必须执行以下操作:

@foreach($apelistoArray as $data)
{{$data}}
@endforeach

答案 1 :(得分:2)

无需循环:-

$response['promotions']['promotion'][0]['appliesto'] = explode(',',$response['promotions']['promotion'][0]['appliesto']);

但是如果promotions可以有多个子数组,请执行以下操作:-

@foreach($response['promotions']['promotion'] as &$value)
   $value['appliesto'] = explode(',',$value['appliesto']);
@endforeach

参考:-explode()