【问题标题】:How to arrange the data of arrays?如何排列数组的数据?
【发布时间】:2019-12-18 20:37:16
【问题描述】:

我有这个 json_decode 数组:

"[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]"

为他们dd:

我需要这样安排它们:

pracetamol - cabsol - 2 - 77

bandol - bottol - 4 - 99

我使用了这段代码,但不能像我需要的那样工作:

$decoded = json_decode($doctor->pharmacys, true);

@foreach($decoded as $d)

  @foreach($d as $k => $v) 
    {{"$k - $v\n"}} <br>
  @endforeach

@endforeach

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您可以使用此代码更好地排列数据:

    $decoded = json_decode($doctor->pharmacys, true);
    $result = [];
    foreach($j as $k1 => $v1){
        $i=0;
        foreach($v1 as $k2 => $v2){
            isset($result[$i]) ? array_push($result[$i],$k2,$v2) : $result[$i] = [$k2,$v2];
            $i++;
        }
    }
    

    结果:

    Array
    (
        [0] => Array
            (
                [0] => pracetamol
                [1] => cabsol
                [2] => 2
                [3] => 77
            )
    
        [1] => Array
            (
                [0] => bandol
                [1] => bottol
                [2] => 4
                [3] => 99
            )
    
    )
    

    在巴德:

    @foreach($result as $d)
    
      @foreach($d as $v) 
        {{$v}} @if(!$loop->last) - @endif
      @endforeach
    
      @if(!$loop->last) <br> @endif
    
    @endforeach
    

    【讨论】:

      【解决方案2】:

      您可以在 PHP 中执行以下操作:

      $a = '[{"pracetamol":"cabsol","bandol":"bottol"},{"2":"77","4":"99"}]';
      $b = json_decode($a, true);
      $k1 = array_keys($b[0]);
      $k2 = array_keys($b[1]);
      
      for ($i = 0; $i < count($k1); $i++) {
          echo $k1[$i]." - ".$b[0][$k1[$i]]." - ".$k2[$i]." - ".$b[1][$k2[$i]]."\n";
      }
      

      这里的技巧是获取每个数组的键列表(在我的示例中命名为 $k1 和 $k2)。这些列表应遵循与关联数组中相同的顺序。 此外,如果您需要访问他们的索引,您可以使用array_search,如answer 中所述。

      【讨论】:

        【解决方案3】:

        我使用CollectionTinker Well,这是我能想到的最佳方法:

        $array = [
            [
                'pracetamol' => 'cabsol',
                'bandol' => 'bottol'
            ],
            [
                '77' => 2,
                '99' => 4
            ]
        ];
        
        $texts = collect($array[0])->map(function ($text, $key) {
            return "$key - $text";
        });
        
        $numbers = collect($array[1])->map(function ($number, $key) {
            return "$number - $key";
        });
        
        $texts
            ->zip($numbers)
            ->mapSpread(function ($linkedText, $linkedNumber) {
                return "$linkedText - $linkedNumber";
            })
            ->values()
            ->toArray();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-03-18
          • 2014-11-29
          • 1970-01-01
          • 2021-07-26
          • 1970-01-01
          • 2018-06-29
          • 1970-01-01
          相关资源
          最近更新 更多