PHP求助键来自多维数组

时间:2011-12-15 17:23:10

标签: php sorting multidimensional-array

我有一个多维数组,其索引/键(不是值)是这样的:

这是提交的数组的外观

  [param] => Array
            (
                [3] => groupedlista
                [0] => groupedlistb
                [2] => groupedlistc
            )

        [f_name] => Array
            (
                [3] => grouplistaa
                [0] => grouplistbb
                [2] => grouplistcc
            )

        [f_label] => Array
            (
                [3] => grouplistL3
                [0] => grouplistL0
                [2] => grouplistL2
            )

这是订单的外观

0,2,3

我想要那个结果

  [param] => Array
            (
                [0] => groupedlistb
                [1] => groupedlistc
                [2] => groupedlista
            )

        [f_name] => Array
            (
                [0] => grouplistbb
                [1] => grouplistcc
                [2] => grouplistaa
            )

        [f_label] => Array
            (
                [0] => grouplistL0
                [1] => grouplistL2
                [2] => grouplistL3
            )

就是这样

PS:我在表单中使用jquery排序/添加/删除功能,我更喜欢做基于php的最终排序。索引数组[$ i]需要在表单中声明。

1 个答案:

答案 0 :(得分:1)

$order = '0,2,3';

$out = array(); // This will hold the sorted values
$order = explode(',',$order); // Turn the order into an array
foreach ($multiDimArray as $key => $subArray) { // Loop outer array
  foreach ($order as $pos) { // Loop order array
    if (isset($subArray[$pos])) { // Make sure the key exists
      $out[$key][] = $subArray[$pos]; // Put the correct value in the correct place
    }
  }
}

print_r($out);