将字符串值与 PHP/Laravel 中的字符串数组进行比较?

Compare string value against array of strings in PHP/ Laravel?

我想匹配字符串和数组。我正在从数据库中的状态 table 中检索状态代码...我有一个带有代码和名称的 json 文件...根据从数据库返回的状态代码,我需要匹配此代码json 文件并在 foreach 中显示状态名称

请大家帮忙

谢谢

状态码数组

[
 {
     "code":"0",
     "name":"AB"
   },
   {
     "code":"1",
     "name":"CD"
   },
   {
     "code":"2",
     "name":"XY"
   },
   {
     "code":"10",
     "name":"EF"
   },
   {
     "code":"12",
     "name":"FG"
   }
 ]

 <?php $findproducts = \DB::table('status')->select('id', 'status_name', 'ab', 'status_code','created_at')->where('ab', $track->ab)->orderBy('id', 'DESC')->get(); ?>
                                         

字符串位置....

 @foreach($findproducts as $pr) 
  @if($statuscodes != null)
   @foreach ($statuscodes as $stcode) 
     @if (strpos($pr->status_code, $stcode['code']) !== FALSE) 
       {{ $stcode['name']." " .$stcode['code'] }}                                                             
     @endif
   @endforeach
@endif
@endforeach

我从上面得到的输出是
CD 1 XY 2 FG 12
CD 1 AB 0 EF 10
XY 2
CD 1
AB 0
预期输出应为
FG 12
英孚 10
XY 2
CD 1
AB 0

你为什么这样做:

@if (strpos($pr->status_code, $stcode['code']) !== FALSE)
    {{ $stcode['name']." ".$stcode['code'] }}
@endif

而不是:

@if ($pr->status_code === $stcode['code'])
    {{ $stcode['name']." ".$stcode['code'] }}
@endif

我认为你的问题是 strpos(我不确定你为什么要使用它)。正如文档所说:Prior to PHP 8.0.0, if needle is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the needle should either be explicitly cast to string, or an explicit call to chr() should be performed.

我不确定你的针是否被用作数字所以它把事情搞砸了...

此外,当 if 为真并且您打印所需内容时,您可以打破 foreach 这样您就不会浪费时间和精力来迭代您知道永远不会出现的内容再次为真,直到发生变化。您可以使用 @break.

@if($statuscodes != null)
    @foreach($findproducts as $pr)
        @foreach ($statuscodes as $stcode)
            @if ($pr->status_code === $stcode['code'])
                {{ $stcode['name']." ".$stcode['code'] }}
                @break
            @endif
        @endforeach
    @endforeach
@endif

另请参阅我已将 foreach 切换为第一个 if,因为如果您没有 $statuscodes,为什么要迭代 $findproducts 和跳过一切?甚至不要重复它...

试试这个,更干净

首先将状态码转换成集合,然后转换成键=>值对的集合

这应该是状态码合集

然后使用简单的 foreach 循环查找您的密钥。

请注意,我不确定从数据库返回的是什么,因此您可以更改代码以适应所需的输出。

也尽量避免嵌套循环

$status_code = collect(json_decode('[
 {
     "code":"0",
     "name":"AB"
   },
   {
     "code":"1",
     "name":"CD"
   },
   {
     "code":"2",
     "name":"XY"
   },
   {
     "code":"10",
     "name":"EF"
   },
   {
     "code":"12",
     "name":"FG"
   }]'
 ,true))->pluck('code','name');



@foreach($findproducts as $pr)
{{$pr->status_code ." ". $status_code[$pr->status_code]}}
@endforeach