簡體   English   中英

多維數組PHP

[英]Multi dimensional array PHP

我有一個這樣的數組

 $array = [
            [
                'relation' => 'AND',
                [
                    'key1' => ['dog', 'dog'],
                    'key2' => [1, 2, 3]
                ],
            ],
            [
                'relation' => 'OR',
                [
                    'key1' => ['cat', 'cat'],
                    'key2' => [7, 8, 9]
                ],
                [
                    'key1' => ['cow', 'cow'],
                    'key2' => [7, 11, 9]
                ],
            ]
        ];

我正在嘗試擁有這樣的 output

$output = [
            'animals'=>[
                'relation' => 'AND',
                [
                    'key1' => 'dog', //convert to a single item
                    'key2' => [1, 2, 3]
                ],
                [ // array at subsequent index is pushed into the array
                    'relation' => 'OR',
                    [
                        'key1' => 'cat',
                        'key2' => [7, 8, 9]
                    ],
                    [
                        'key1' => 'cow',
                        'key2' => [7, 11, 9]
                    ],
                    // [
                    //     ....subsequent array is pushed into the array
                    // ]
                ]           
            ]
        ];

我嘗試使用數組 map 來合並重復值,然后迭代但不知道如何解決它,我真的很感激一些解決這個問題的方法。

此迭代將解決您的重復問題,然后您可以使用$array
array_unique($item)這個 function 接受一個輸入數組並返回一個沒有重復值的新數組。

foreach($array as $key1 => $items){
    for($i = 0; $i < count($items)-1; $i++){
        foreach($items[$i] as $key2 => $item){
            $uniqueArr= array_unique($item);
            $array[$key1][$i][$key2]= $uniqueArr;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM