1

我有 2 个 PHP 数组,第一个存储值,第二个存储键,如下所示:

  1. ['first designer', 'shirt', 'cloth1', 'cloth2', 'second designer']
  2. ['designer', 'brand', 'category', 'category', 'designer']

我想转换这些数组,以便我可以按以下格式输出它们,根据第二个数组的相应元素对第一个数组中的项目进行分组:

  <div id="category">
  cloth1
  cloth2
  </div>

  <div id="brand">
  shirt
  </div>

  <div id="designer">
  first designer
  second desinger
  </div>
4

1 回答 1

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>

键盘http ://codepad.org/T7NmPyVR

于 2012-07-18T18:41:39.460 回答