php - 减少和合并数组

标签 php mysql laravel

我正在尝试创建一个简洁地为我提供以下内容的数组:

  • 组成部分的ID
  • 该组件的供应商 ID
  • 数量断点及其相关的单位成本

我使用的是 Laravel 5.2,尽管这是一个更一般的 PHP 问题。

所以,我有一个如下所示的数据库表:

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 组,都有一组“卷”。

非常感谢任何建议...我已经尝试了几个小时来对数组进行排序!

最佳答案

在Mysql中,你可以这样做

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

然后您可以简单地在 PHP 中循环此查询并通过逗号分解卷字段。

关于php - 减少和合并数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38228126/

相关文章:

laravel - 如果设备 token 不再有效,我想处理 fcm 生成的异常

php Laravel 只允许连续最多两个换行符

php - LAMP 当我上传 php 代码时,但浏览器不会刷新,直到我在 Linux 中重新启动 apache2 服务

php - PHP 类文件的静态路径还是相对路径?

php - 未找到 MySQL 表,但它存在

mysql - 创建表失败

php - mysql从while外部获取数据

mysql - Laravel 权限在远程 Mysql 服务器 (AWS aurora) 上被拒绝

javascript - 从 jquery POST 数据中选择一个元素

mysql - DBI 连接 ('database=orthomcl;host=db;mysql_local_infile=1' ,'orthomcl' ,...) 失败 : Access denied for user