如何在php中对左连接查询返回的数组数据进行分组?

时间:2017-12-02 21:11:59

标签: php mysql join

我有以下2个表,其中包含以下值:

tbl_brand

ID 命名

1苹果

2三星

tbl_products

ID brand_id p_name

1 1移动

2个1 Earpods

3 2移动

此处我使用左连接查询i.e.

SELECT 'b'.'id' as 'brand_id', 'b'.'name' as 'brand_name', 'p'.'p_name' as 'product_name' FROM 'tbl_brand' 'b' LEFT JOIN 'tbl_products' 'p' ON 'p'.'brand_id' = 'b'.'id'

并打印结果,我得到以下数组:

Array
    (
        [0] => stdClass Object
            (
                [brand_id] => 1
                [brand_name] => Apple
                [product_name] => Mobile
            )
        [1] => stdClass Object
            (
                [brand_id] => 1
                [brand_name] => Apple
                [product_name] => Earpods
            )
        [2] => stdClass Object
            (
                [brand_id] => 2
                [brand_name] => Samsung
                [product_name] => Mobile
            )

一切都很好。但我正在寻找的结果是这样的:

Array
    (
        [0] => stdClass Object
            (
                [brand_id] => 1
                [brand_name] => Apple
                [product_name] => stdClass Object
                               (
                                   [0] => Mobile
                                   [1] => Earpods
                               )
            )
        [1] => stdClass Object
            (
                [brand_id] => 2
                [brand_name] => Samsung
                [product_name] => Mobile
            )

我想根据brand_id键对数据进行分组。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

虽然您可以在单个循环中生成所需的数组,但我宁愿执行两个查询。首先将所有品牌整合到一个阵列中,并为每个品牌添加一个空产品阵列。然后获取所有产品并将其分配给相关品牌。

由于我不知道你正在使用什么数据库库,这里有一些伪代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

//CreditCard class
public class CreditCard {
    //Variable declaration

    private JFrame frame;
    private JPanel panel;
    private JTextField textField;
    private JLabel label;
    private JLabel resLabel;
    private JButton validateBtn;

    //Constructor
    public CreditCard() {

        frame = new JFrame("Credit Card Details");
        frame.setSize(350, 350);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // create a new panel and add the frame to the panel.
        panel = new JPanel();
        frame.add(panel);
        panel.setLayout(null);

        // add label
        label = new JLabel("Enter Credit Card No.");
        label.setBounds(10, 20, 165, 25);
        panel.add(label);

        // add input text
        textField = new JTextField(16);
        textField.setBounds(10, 50, 165, 25);
        panel.add(textField);

        // create a validation button
        validateBtn = new JButton("Validate");
        validateBtn.setBounds(10, 80, 80, 25);
        panel.add(validateBtn);

        frame.setVisible(true);

        // set label as valid or invalid
        resLabel = new JLabel();
        resLabel.setBounds(180, 50, 265, 25);
        panel.add(resLabel);

        // add event listener
        validateBtn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                String text = textField.getText();
                if (text.length() < 13 || text.length() > 16) {
                    resLabel.setText("Entered Value Must Be Between 13-16 Chars");
                    return;
                }
                boolean isValid = validateText(text);
                if(isValid)
                    resLabel.setText("Credit Card is Valid");
                else
                    resLabel.setText("Credit Card is Invalid");
                }catch(NumberFormatException f){
                    System.out.println("Enter Valid Card Number");
                }

            }

            private boolean validateText(String text) {
                int rSum = 0, lSum = 0;
                for (int i = text.length() - 2; i >= 0; i -= 2) {
                    if (!Character.isDigit(text.charAt(i)))
                        return false;
                    int currentNum = Character.getNumericValue(text.charAt(i));
                    currentNum *= 2;
                    if (currentNum > 9) {
                        int tempSum = 0;
                        while (currentNum >= 10) {
                            tempSum += currentNum % 10;
                            currentNum /= 10;
                        }
                        tempSum += currentNum;
                        currentNum = tempSum;
                    }
                    rSum += currentNum;
                }
                System.out.println(rSum);
                for (int i = text.length() - 1; i >= 0; i -= 2) {
                    if (!Character.isDigit(text.charAt(i)))
                        return false;
                    int currentNum = Character.getNumericValue(text.charAt(i));
                    lSum += currentNum;
                }
                System.out.println(lSum);
                int totalSum = lSum + rSum;
                if (totalSum % 10 == 0)
                    return true;
                return false;
            }

        });
    }
}

答案 1 :(得分:0)

mysql返回行,所以如果你想要一个多维数组,你必须自己构建它。沿着这些线的循环将会这样做:

$array=array();
foreach ($result as $row) {
    $array[$row->brandid]['brandid'] = $row->brandid;
    $array[$row->brandid]['brand_name'] = $row->brand_name;
    $array[$row->brandid]['products'][] = $row->product;
    }