我有2个PHP数组,第一个存储值,第二个存储键,如下所示:
['first designer', 'shirt', 'cloth1', 'cloth2', 'second designer']
['designer', 'brand', 'category', 'category', 'designer']
我想转换这些数组,以便我可以按以下格式输出它们,根据第二个数组的相应元素对第一个数组中的项进行分组:
<div id="category">
cloth1
cloth2
</div>
<div id="brand">
shirt
</div>
<div id="designer">
first designer
second desinger
</div>
答案 0 :(得分:2)
试试这个:
<?php
$foo = array("designer", "brand", "category", "category", "designer");
$bar = array("first designer", "shirt", "cloth1", "cloth2", "second designer");
$baz = array();
for ($i = 0; $i < sizeof($foo); $i++) {
$baz[$foo[$i]][] = $bar[$i];
}
foreach ($baz as $key=>$values) {
echo '<div id="' . $key . '">
';
foreach ($values as $value) {
echo ' ' . $value . '<br />
';
}
echo '</div>
';
}
?>
这将输出:
<div id="designer">
first designer<br />
second designer<br />
</div>
<div id="brand">
shirt<br />
</div>
<div id="category">
cloth1<br />
cloth2<br />
</div>