在这种情况下如何删除数组?

时间:2020-03-10 02:17:09

标签: php

我有以下内容:

array(
    array(
    [Title] => Bsapwut cljxte qee poaof aazait
    [Section] => videos
    [Category1] => teste
    [Category2] => teste2
    ),
    array(
    [Title] => Bsapwut cljxte qee poaof aazait
    [Section] => articles
    [Category1] => teste
    [Category2] => teste2
    ),
    array(
    [Title] => Bsapwut cljxte qee poaof aazait
    [Section] => videos
    [Category1] => teste
    [Category2] => teste2
    )
);

请注意,在第二个数组中,项目“节”接收到“文章”。我需要从父数组中删除所有包含section并依次收到“文章”的数组。所有其他将“部分”作为“视频”的数组都必须保留。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

$arr = array(
        array(
            'Title' => 'Bsapwut cljxte qee poaof aazait',
            'Section' => 'videos',
            'Category1' => 'teste',
            'Category2' => 'teste2',
        ),
        array(
            'Title' => 'Bsapwut cljxte qee poaof aazait',
            'Section' => 'articles',
            'Category1' => 'teste',
            'Category2' => 'teste2',
        ),
            array(
            'Title' => 'Bsapwut cljxte qee poaof aazait',
            'Section' => 'videos',
            'Category1' => 'teste',
            'Category2' => 'teste2',
        )
    );

方法1.使用数组过滤器

$filteredArr = array_filter($arr, function ($inArr) {
    return ( array_key_exists('Section', $inArr) && $inArr['Section'] == 'videos' );
});
echo "<pre>";
print_r($filteredArr);

方法2。Foreach和Unset()

foreach ($arr as $index => $inArr) {
    if (!empty($inArr['Section']) && $inArr['Section'] == 'articles') {
        unset($arr[$index]);
    }
}

echo '<pre>';
print_r($arr);