基于类别,设计师和品牌组合阵列,并根据类别,品牌,设计师划分阵列

时间:2012-07-18 18:37:00

标签: php arrays

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

  1. ['first designer', 'shirt', 'cloth1', 'cloth2', 'second designer']
  2. ['designer', 'brand', 'category', 'category', 'designer']
  3. 我想转换这些数组,以便我可以按以下格式输出它们,根据第二个数组的相应元素对第一个数组中的项进行分组:

      <div id="category">
      cloth1
      cloth2
      </div>
    
      <div id="brand">
      shirt
      </div>
    
      <div id="designer">
      first designer
      second desinger
      </div>
    

1 个答案:

答案 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>

键盘http://codepad.org/T7NmPyVR