在另一个数组中按键组合关联数组

时间:2014-07-05 19:30:16

标签: php html arrays

我想将我的二维数组显示到html表中,其中类似的值应该组合/合并到一个单元格中。 例如,我有一个数组: -

$final_arr = array(
    array(
        "id"      => "106",
        "name"    => "Fashion",
        "asset"   => "project",
        "assetid" => "2708",
        'version' => "2.16.22"
    ),
    array(
        "id"      => "2",
        "name"    => "Sports",
        "asset"   => "project",
        "assetid" => "2758",
        'version' => "2.16.26"
    ),
    array(
        "id"      => "106",
        "name"    => "Fashion",
        "asset"   => "tracking",
        "assetid" => "2758",
        'version' => "2.15.16"
    ),
    array(
        "id"      => "153",
        "name"    => "Giyan",
        "asset"   => "character",
        "assetid" => "2694",
        'version' => "2.20.6"
    )
); 

现在我想将上述结果集显示为html表格: -

 ID          Asset             Version  

106          project           2.16.22
             tracking          2.16.26  
2            Sports            2.15.16
153          Giyan             2.20.6   

有人可以提供有关如何实现这一目标的见解吗?

非常感谢!!

1 个答案:

答案 0 :(得分:0)

我可能会后悔回答这个问题,但这是一个简单易懂的解决方案。

使用id作为索引(键)创建一个新数组。

$newArray = array();
foreach ($yourArray as $array) {
    $filter = $array;
    unset($filter['id']);
    $newArray[$array['id']][] = $filter;
}

然后在你的表中:

<table>
<thead>
    <tr>
        <th>ID</th>
        <th>Asset</th>
        <th>Version</th>
    </tr>
</thead>
<tbody>
<?php foreach ($newArray as $id => $array): ?>
    <?php $count = 0; ?>
    <?php foreach ($array as $arr): ?>
    <tr>
        <td><?= (++$count <= 1) ? $id : ''; ?></td>
        <td><?= $arr['asset']; ?></td>
        <td><?= $arr['version']; ?></td>
    </tr>
    <?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>