根据键取消设置特定祖先的嵌套后代,如果为空,则也取消设置祖先

时间:2019-05-31 19:49:56

标签: php

假设我们有一个包含嵌套数组的多维数组

$arr = [
    1 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
            1 => [
                'id' => 3,
                'products' => [],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
    4 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
];

我需要将所有祖先和后代保持在键“产品”中至少有一项的位置,所有其他阵列都应未设置。

因此,在此特定示例中,结果应如下所示:

$arr = [
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
];

基本上,需要做的是从最内部的数组开始并询问:

1)我们的关键“产品”是否为空?是的

2)我们的关键“家庭”是否为空或未设置?是的

3)取消设置该数组

2 个答案:

答案 0 :(得分:0)

此函数确定数组或其任何后代是否具有乘积。

function has_products($x) {
    return is_array($x) && (!empty($x['products']) || array_filter($x, 'has_products'));
}

您可以使用它来过滤数组。

$arr = array_filter($arr, 'has_products');

或作为匿名函数:

$arr = array_filter($arr, $filter = function ($x) use (&$filter) {
    return is_array($x) && (!empty($x['products']) || array_filter($x, $filter));
});

答案 1 :(得分:-1)

您可以这样做:

<?php

$arr = [
    1 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
    2 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2,
                'products' => [
                    1 => 'John Doe'
                ],
            ],
            1 => [
                'id' => 3,
                'products' => [],
            ],
        ]
    ],
    3 => [
        'id' => 1,
        'products' => [
            1 => 'Hi',
            2 => 'Hello',
        ]
    ],
    4 => [
        'id' => 1,
        'families' => [
            0 => [
                'id' => 2
            ],
            1 => [
                'id' => 3
            ],
        ]
    ],
];

foreach($arr as $k => $a) {
    if(strpos(json_encode($a), "products") == 0){
        unset($arr[$k]);
    }
}

var_dump($arr);

https://3v4l.org/tNSqs