简体   繁体   中英

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 = [
            '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.

This iteration will solve your duplicate issue, then you can use $array
array_unique($item) This function takes an input array and returns a new array without duplicate values.

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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM