猿问

PHP 按 3 个字段对 PDO 或 JSON 结果进行分组并输出

我正在尝试按 3 个字段 Delivery_date、van_no 和 drop_no 将结果分组到一个数组中,这是我到目前为止所拥有的:


// Gets all orders and sorts by delivery date, van and drop number

    $getorders = $conn->prepare("SELECT * FROM orders INNER JOIN customers ON orders.customer_id = customers.customer_id INNER JOIN addresses on orders.address_id = addresses.address_id ORDER BY delivery_date, van_no, drop_no");

    $getorders->execute();


    $result = $getorders->fetchAll(\PDO::FETCH_ASSOC);    


    var_dump($result);

这给了我这样的输出:


array (size=6)

  0 => 

    array (size=8)

      'orders_id' => string '6' (length=1)

      'customer_id' => string '1' (length=1)

      'address_id' => string '1' (length=1)

      'van_no' => string '1' (length=1)

      'drop_no' => string '0' (length=1)

      'delivery_date' => string '2020-08-25' (length=10)

      'customer_name' => string 'One' (length=3)

      'address_postcode' => string 'b1' (length=2)

  1 => 

    array (size=8)

      'orders_id' => string '1' (length=1)

      'customer_id' => string '1' (length=1)

      'address_id' => string '1' (length=1)

      'van_no' => string '1' (length=1)

      'drop_no' => string '1' (length=1)

      'delivery_date' => string '2020-08-25' (length=10)

      'customer_name' => string 'One' (length=3)

      'address_postcode' => string 'b1' (length=2)

  2 => 

    array (size=8)

      'orders_id' => string '3' (length=1)

      'customer_id' => string '2' (length=1)

      'address_id' => string '2' (length=1)

      'van_no' => string '1' (length=1)

      'drop_no' => string '2' (length=1)

      'delivery_date' => string '2020-08-25' (length=10)

      'customer_name' => string 'Two' (length=3)

      'address_postcode' => string 'b2' (length=2)

如果我将其更改为 \PDO::FETCH_GROUP ,它似乎只是将每个数组的每个字段加倍,如果我在查询中使用 GROUP BY ,它只会为每个字段提供一个结果。我试过了:


 foreach($data->delivery_date as $values)

 {

      echo $values->van_no . "\n";

 }

但请注意:尝试获取非对象的属性“delivery_date”,我尝试编码为 JSON,但陷入困境并尝试分组。


基本上我现在完全迷失了,我在谷歌上搜索的有关 PDO 数组或 JSON 数组分组的所有内容最终都没有执行任何操作或抛出如上所述的错误。


噜噜哒
浏览 108回答 1
1回答

料青山看我应如是

输出..."delivery_date": "2020-08-25"    {无法实现,因此此代码将创建输出,其中包含送货和货车列表......$output = [];while( $result = $getorders->fetch(\PDO::FETCH_ASSOC))  {    if ( !isset($output[$result['delivery_date']]) )    {        $output[$result['delivery_date']]['date'] = $result['delivery_date'];    }    if ( !isset($output[$result['delivery_date']][$result['van_no']]) ) {        $output[$result['delivery_date']][$result['van_no']]['van']             = $result['van_no'];    }    $output[$result['delivery_date']]            [$result['van_no']][] = $result;}echo json_encode(array_values($output), JSON_PRETTY_PRINT);这会给你一些类似...[    {        "date": "2020-08-25",        "1": {            "van": 1,            "0": {                "delivery_date": "2020-08-25",                "van_no": 1,
随时随地看视频慕课网APP
我要回答