通过内部索引安排PHP多维数组

时间:2012-07-27 07:19:46

标签: php arrays multidimensional-array

如何按最后一个内部索引(0,1,2)排列这个数组,并获取最后一个内部索引的值作为每个第二个索引的值:

Array
(
    [text] => Array
        (
            [grid] => Array
                (
                    [0] => 3
                    [1] => 4
                    [2] => 5
                )

            [image] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

            [align] => Array
                (
                    [0] => left
                    [1] => right
                    [2] => left
                )

            [title] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

            [content] => Array
                (
                    [0] => 
                    [1] => 
                    [2] => 
                )

        )

)

结果如下:

Array
(
    [text] => Array
        (
            [0] => Array
                (
                    [grid] => 3
                    [image] => 
                    [align] => left
                    [title] => 
                    [content] => 
                )

            [1] => Array
                (
                    [grid] => 4
                    [image] => 
                    [align] => right
                    [title] => 
                    [content] => 
                )

            [2] => Array
                (
                    [grid] => 5
                    [image] => 
                    [align] => left
                    [title] => 
                    [content] => 
                )

        )

)

3 个答案:

答案 0 :(得分:2)

这将完成工作

function restructure($arr){
    $newArr = array();
    foreach($arr as $k => $v){
        foreach($v as $k1 => $v1){
            foreach($v1 as $k2 => $v2){
                $newArr[$k][$k2][$k1] = $v2; 
            }
        }
    }
    return $newArr;
}

答案 1 :(得分:1)

for/foreach循环之外的其他方式:

function buildArray($source, $key = false)
{
    // Build the new array
    $new_array = array();
    // Define groups
    $groups = $key === false ? array_keys($source) : array($key);

    foreach($groups AS $group)
    {
        // Get the keys
        $keys = array_keys($array[$group]);
        // Count the values
        $num_entries = count($array[$group][$keys[0]]);

        for($i = 0; $i < $num_entries; $i++)
        {
            foreach($keys AS $key)
            {
                $new_array[$group][$i][$key] = $array[$group][$key][$i];
            }
        }
    }
    return $new_array;
}

这允许您定义构建所需的密钥;如果未指定,则该函数为每个键构建数组。

答案 2 :(得分:0)

这应该有用。

function formatit($arr) {

  $new = array();

  foreach($arr as $k=>$v) {
    foreach($v as $k1=>$v1) {
     $new[$k1][$k] = $v1;
    }
  }
  return $new;
}

测试。将其称为

$arr['text'] = formatit($arr['text']);

http://ideone.com/rPzuR