循环遍历多维数组

时间:2016-12-08 00:58:58

标签: php arrays multidimensional-array

所以我有一个像这样的数组:

$arr = array(
  "element1"  => array("group" => "g1", "other_stuff" => "foo"),
  "element2"  => array("group" => "g1", "other_stuff" => "bar"),
  "element3"  => array("group" => "g1", "other_stuff" => "foo"),
  "element4"  => array("group" => "g2", "other_stuff" => "bar"),
  "element5"  => array("group" => "g2", "other_stuff" => "foo"),
  "element6"  => array("group" => "g2", "other_stuff" => "bar"),
  "element7"  => array("group" => "g3", "other_stuff" => "foo"),
  "element8"  => array("group" => "g3", "other_stuff" => "bar"),
  "element9"  => array("group" => "g3", "other_stuff" => "foo"),
);

我想在每个组中以洗牌顺序显示元素,前面是组,组的顺序也被洗牌。例如:

g2
-> element5
-> element4
-> element6
g3
-> element7 
-> element9
-> element8
g1
-> element2 
-> element3
-> element1

我以为我可以沿着这条路做点什么:

shuffle($arr);

foreach($arr[]["group"] as $current_group){
    echo "$current_group"
    foreach($arr[][$current_group] as $current_element){
        echo "-> ".$ current_element."<br />"
    }
}

但不,$arr[]["group"]无效。我怎样才能做到这一点?

由于

(现在是凌晨2点,我的伪代码可能会破碎,对不起,我只是想传达我的想法)

1 个答案:

答案 0 :(得分:3)

首先使用group值对它们进行分组。将其用作新容器分配中的键:

$final_arr = array();
foreach($arr as $key => $a) {
    $final_arr[$a['group']][] = $key;
}

这应该产生以下结构:

Array
(
    [g1] => Array
        (
            [0] => element1
            [1] => element2
            [2] => element3
        )

    [g2] => Array
        (
            [0] => element4
            [1] => element5
            [2] => element6
        )

    [g3] => Array
        (
            [0] => element7
            [1] => element8
            [2] => element9
        )

)

现在由您决定如何呈现它(仅通过简单的->字符串或HTML)。

肮脏的例子:

echo '<ul>';
foreach($final_arr as $group => $f) {
    echo '<li>', $group;
    echo '<ul>'; foreach($f as $e) { echo "<li>{$e}</li>"; } echo '</ul>';
    echo '</li>';

}
echo '</ul>';

如果您希望保留shuffle,只需将密钥随机播放并传输即可:

$keys = array_keys($arr); // get the keys of the original
shuffle($keys); shuffle the keys
$new_arr = array(); // initialize a temp container
foreach($keys as $k) {
    $new_arr[$k] = $arr[$k]; // match the shuffled key and assign it
}
$arr = $new_arr; // overwrite