简体   繁体   English

多维数组PHP

[英]Multi dimensional array PHP

I have an array like this我有一个这样的数组

 $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]
                ],
            ]
        ];

I am trying to have an output like this我正在尝试拥有这样的 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
                    // ]
                ]           
            ]
        ];

I tried using array map to merge the duplicate values and then iterate but not sure how to solve it, would really appreciate some approach to solve this.我尝试使用数组 map 来合并重复值,然后迭代但不知道如何解决它,我真的很感激一些解决这个问题的方法。

This iteration will solve your duplicate issue, then you can use $array此迭代将解决您的重复问题,然后您可以使用$array
array_unique($item) This function takes an input array and returns a new array without duplicate values. 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