将多个foreach循环值存储到一个数组中以在PHPExcel中使用

时间:2019-01-16 14:58:22

标签: php arrays phpexcel

我当前正在循环使用以下结构的数组:

Categories{
    CategoryName
    CategoryCode
    CategoryDescription

    Products{
        product_info{
            product_code
            product_type{
                CountNumber
                ProductDescription
            }
        }
        prices{
        "wholesale":"250",
        "retail":"400"
        }
    }   
}    

我在每个级别上循环上述数组,并声明了一个数组,以便可以将所有需要的值放入其中

$priceResult = array();

foreach($prices->categories as $category){ 
    $categoryName = $category->category_name;
    $categoryCode = $category->category_code;
    $categoryDescription = $category->category_desc;

    foreach($category->products as $product){

        foreach($product->product_info as $info){
            $product_code = $info->product_code;
            foreach($info->product_type as $type){
                $CountNumber = $type->CountNumber;
                $ProductDescription = $type->ProductDescription;
            }
        }
        foreach ($product->prices as $price => $amount) {
            $price_amount = $amount;

        }
    }
}

我遇到的问题是我不知道如何正确地推入新的$priceResult数组,这样我才能使用PHPExcel将其转换为带有副标题的格式。

在上面的示例中,我想要的格式将是这样

    Test Category 1  |  123  |   Category for Testing
    ==================================================
    PRD123 |  12  |  Product for Testing  |  150.00
    PRD112 |  17  |  Product for Testing  |  250.00

    Test Category 2  |  321  |   New Category for Testing
    =====================================================
    PRD189 |  16  |  Product for Testing  |  450.00
    PRD139 |  34  |  Product for Testing  |  350.00

因此,基本上我想在$ priceResult数组上调用PHPExcel,以获取可以在其中列出类别信息的格式,并且对于该类别中的每个产品,我都会有一个产品行。一切都将按类别主标题分组

    $build = Excel::create($name, function ($excel) use ($priceResult) {

    $excel->setTitle('Test Products');

更新:

所以我在想我想要的结果数组应该是这样的:

CategoryCode : 123
CategoryName : TestCategory
CategoryDescription: For Testing
    Products{
        0{
            Product_code : 123,
            CountNumber : 12,
            ProductDescription: Test Product,
            price_amount : 150.00
        },
        1{
            Product_code : 112,
            CountNumber : 32,
            ProductDescription: Test Product 2,
            price_amount : 250.00
        }
    }

这样,每个类别都可以是标题,并且其所有产品可以是每个类别的行

0 个答案:

没有答案