从具有特定类的div中的多维数组中包含每3个元素

时间:2016-01-13 14:12:16

标签: php arrays

我有这一系列产品:

$products = array(
0 => array(
"name" => "product1",
),
1 => array(
"name" => "product2",
),
2 => array(
"name" => "product3",
),
3 => array(
"name" => "product4",
),
4 => array(
"name" => "product5",
),
5 => array(
"name" => "product6",
 ),
);

在每一行我都可以拥有3种产品。我需要将这些产品包装在一个div中,其中包含class gray_div,其他3个产品包含在一个带有blue_div类的div中。

<div class="gray_div">
 product1   product 2 product 3
</div>

<div class="blue_div">
 product4   product 5 product 6
</div>

2 个答案:

答案 0 :(得分:2)

检查PHP中的array_chunk()

$newArray = array_chunk($products, 3);
foreach ($newArray as $key => $product) {
    echo '<div class="'.(($key % 2) ? "blue_div" : "gray_div").'">';
    foreach ($product as $p) {
        echo $p['name']." ";
    }
    echo '</div>'.PHP_EOL;
}

答案 1 :(得分:1)

使用array_chunkarray_walk_recursive来压缩块并一次性完成所有操作。

$chunks = array_chunk($products,3);

foreach($chunks as $key=>$chunk){

    $products = [];

    array_walk_recursive($chunk, function($value) use (&$products) {
        $products[] = $value; 
    });


    if ($key%2==0){
        $color = 'gray';
    }
    else{
        $color = 'blue';
    }

    print '<div class="' . $color . '_div">' . implode(' ',$products) . '</div>' . PHP_EOL;
}

将输出

<div class="gray_div">product1 product2 product3</div>
<div class="blue_div">product4 product5 product6</div>