在Foreach中打印数组键多维

时间:2016-05-09 12:40:42

标签: php arrays multidimensional-array

我有一个数组(从excel文件中获取数据),我一直试图"合并"数据取决于ID。我已设法创建阵列(将产品分组到ID),结果如下。

Array ( [Order10] => Array ( [Mr Name] => Array ( [45 STREET] => Array ( [AREA] => Array ( [Product1] => 1 [Product2] => 3 ) ) ) ) )

我现在正试图获取数据(订单,名称,街道等),但我只是设法使用密钥(var)提取ID(Order10)。这是代码当前的基本布局。

//Gets Data from excel file
foreach ($bulk as $prod)
{
    $APIOrder[] = array('Order' => $prod['ORDER'],
                         'Prod' => $prod['PROD'],
                        'Quantity' => $prod['QTY'],
                        'Recipient_Name' => $prod['RECIPIENT_NAME']);
}

$newOptions = array();
foreach ($APIOrder as $option)
{
    $Order = $option['Order'];
    $Prod = $option['Prod'];
    $Qty = $option['Quantity']; //Added
    $Recipient_Name = $option['Recipient_Name'];
    $newOptions[$Order][$Recipient_Name][$Prod] = $Qty;
}

$index4 = 0;

foreach($newOptions as $key=>$val)
{
    $SeperateOptions = (array_slice($newOptions, $index4, true));
    //Print Array to check, Echo ID, Name, Product
    $index4++;
}

如果我在foreach循环中没有代码,我可以提取这些数据。这个问题是订单重复,取决于订单上有多少产品,这使得将订单插入数据库系统更加困难。下面的例子:

Array ( [Order10] => Array ( [Mr Name] => Array ( [45 STREET] => Array ( [AREA] => Array ( [Product1] => 1) ) ) ) )
Array ( [Order10] => Array ( [Mr Name] => Array ( [45 STREET] => Array ( [AREA] => Array ( [Product2] => 3) ) ) ) )

正如我所说,如果我不尝试将所有产品放入数组中,我可以提取数据,但是当数据被发送到数据库以添加时,我将不得不创建一个循环缺少产品。任何方向都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

这不是一个真正的答案,但根据OP和我之间的评论,我试图向他展示,我是如何做到的,这太长了,这里是代码格式化。关键是顺序的id,数组中的每个东西,然后是多于1的值。 products也是一个数组。尽量保持相关的内容。:

$orders = [
    'Order10' => [
        'name' => 'Mr Name',
        'address' => [
            'street' => 'street here',
            'country' => 'country here',
            'zipcode' => 'zipcode here'
        ],
        'phones' => [
            'mobile' => 'mobile phone here',
            'fax' => 'fax here',
            'workplace' => 'here'
        ],
        'products' => [
            'productId1',
            'productId2',
            //and so on
        ]
    ]
];

然后你可以像这样迭代你的订单数组来显示:

foreach ($orders as $order) {
        ?>
        <div>Name: <?php echo $order['name']; ?></div>
        <div>Address: <?php echo $order['address']['zipcode']; ?>, <?php echo $order['address']['country']; ?>, <?php echo $order['address']['street']; ?>    </div>
        <div>Products: 
            <?php
            foreach ($order['products'] as $procutId) {
                $Produt = new Procut($productId);
                ?>
                <div><?php echo $Product->getName(); ?></div>
                <?php
            }
            ?>
        </div>
        <hr>
        <?php
    }
}
?>

在我的示例中,我有一个Product类,也许您没有使用类,但当然,您可以创建一个getProcut($id)函数来获取id的产品,所以它可能是

$product = getProduct($procutId);
echo $product['name'];

这是你的决定。

相关问题