2016-07-06 9 views
3

の削減と組み合わせること:その構成部品サプライヤーのための構成部品 は私が簡潔に私に次を与える配列を作成しようとしている配列

  • IDの

    • ID
    • ボリュームのブレークポイント、関連ユニットコスト

    これはもっと一般的なPHP質問ですが、私はLaravel 5.2を使用しています。

    だから、私はこのようになり、データベースのテーブルを持っている:

    sql screenshot

    私はコンポーネントの一部の価格を取得するには、以下のように、機能を持っている:

    public function get_component_prices() 
        { 
         $components = DB::table('component_supplier') 
          ->select('component_id', 'supplier_id', 'volume', 'unit_cost') 
          ->get(); 
    
         $prices = []; 
    
         foreach ($components as $component) { 
          array_push($prices, ["component_id" => $component->component_id, "supplier_id" => $component->supplier_id, "volumes" => [$component->volume => $component->unit_cost]]); 
         } 
    
         dd($prices); 
        } 
    

    これは私を与えます配列:

    array:7 [▼ 
        0 => array:3 [▼ 
        "component_id" => 3 
        "supplier_id" => 1 
        "volumes" => array:1 [▼ 
         100 => "1.5000" 
        ] 
        ] 
        1 => array:3 [▼ 
        "component_id" => 3 
        "supplier_id" => 1 
        "volumes" => array:1 [▼ 
         207 => "1.0100" 
        ] 
        ] 
        2 => array:3 [▼ 
        "component_id" => 3 
        "supplier_id" => 1 
        "volumes" => array:1 [▼ 
         500 => "0.8000" 
        ] 
        ] 
        3 => array:3 [▼ 
        "component_id" => 3 
        "supplier_id" => 1 
        "volumes" => array:1 [▼ 
         1000 => "0.4000" 
        ] 
        ] 
        4 => array:3 [▼ 
        "component_id" => 3 
        "supplier_id" => 2 
        "volumes" => array:1 [▼ 
         10000 => "0.2000" 
        ] 
        ] 
        5 => array:3 [▼ 
        "component_id" => 4 
        "supplier_id" => 2 
        "volumes" => array:1 [▼ 
         100 => "0.1000" 
        ] 
        ] 
        6 => array:3 [▼ 
        "component_id" => 4 
        "supplier_id" => 2 
        "volumes" => array:1 [▼ 
         500 => "0.0700" 
        ] 
        ] 
    ] 
    

    特定のサプライヤコンポーネントには複数のボリュームがあります。

    6 => array:3 [▼ 
         "component_id" => 4 
         "supplier_id" => 2 
         "volumes" => array:3 [▼ 
          100 => "0.1000", 
          500 => "0.0700" 
         ] 
         ] 
    

    各COMPONENT_IDとSUPPLIER_IDグループのために、ありますようにするには:例えば、おそらくそうのような -

    したがって、私は繰り返し部品を組み合わせ、配列が少し良くグループに試してみたいと思います「ボリューム」のセット。

    何かアドバイスをいただければ幸いです...私は並べ替えられた配列を取得するために何時間も努力してきました!

  • 答えて

    1

    は、MySQLでは、あなたは、あなたがカンマでボリュームフィールドを単にループこのPHPでクエリと爆発することができ、この

    SELECT component_id, supplier_id, 
         GROUP_CONCAT(volume, ':', unit_cost) AS volumes 
    FROM component_supplier 
    GROUP BY CONCAT(component_id, supplier_id) 
    

    http://sqlfiddle.com/#!9/cb7bb/1

    Output of the above query

    ような何かを行うことができます。

    関連する問題