php数组栈排序

时间:2011-02-21 01:53:50

标签: php arrays multidimensional-array no-duplicates

我试图在php中对这个数组进行排序:

Array
(
    [Levi Self] => Array
        (
            [0] => Portraits
            [1] => Abstract
        )

    [Portraits] => Array
        (
            [0] => Megan
        )

    [Abstract] => Array
        (
            [0] => Locks
        )

)

看起来像这样:

Array
(
    [Levi Self] => Array
        (
            [Portraits] => Array
               (
                 [0] => Megan
               )

            [Abstract] => Array
               (
                 [0] => Locks
               )
        )
)

其中,基本上删除了重复的项目“Portraits”和“Abstract”,因为它们已经是数组开始的键,以及第一个键“Levi Self”下的项目。有没有办法做到这一点?谢谢,Levi Self

1 个答案:

答案 0 :(得分:1)


$priKey = "Levi Self";
$arr = array(
    "Levi Self" => array("Portraits","Abstract"),
    "Portraits" => array("Megan"),
    "Abstract" => array("Locks")
);

function rearrangeData($primaryKey,$myArr){
    foreach($myArr[$primaryKey] as $key => $value){
        $myArr[$primaryKey][$value] = $myArr[$value];
        unset($myArr[$primaryKey][$key]);
        unset($myArr[$value]);
    }

    return $myArr;
}

$arr2 = rearrangeData($priKey, $arr);

print_r($arr); //what you started with
print_r($arr2); //what you want