繁体   English   中英

如何在 PHP 中比较两个数组值并获得匹配的内部数组值

[英]How to compare two array value and get matched inner array value in PHP

如何比较两个数组值并从内部数组中删除重复值并使用 PHP 存储在另一个数组中。 由 array[name] 比较的数组,并希望删除所有内部数组中的相关索引。

阵列 1

Array
(
    [0] => detail12.docx
    [1] => resume.docx
)

阵列 2

Array
(
    [name] => Array
        (
            [0] => detail12.docx
            [1] => document.pdf
            [2] => resume.docx
        )

    [type] => Array
        (
            [0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
            [1] => application/pdf
            [2] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
        )

    [tmp_name] => Array
        (
            [0] => /tmp/php2LK7xC
            [1] => /tmp/phpTEWqXG
            [2] => /tmp/phpAKki0M
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
            [2] => 0
        )

    [size] => Array
        (
            [0] => 30887
            [1] => 86118
            [2] => 30887
        )

)

预期 Output:-

Array
(
    [name] => Array
        (
            [0] => detail12.docx
            [1] => resume.docx
        )

    [type] => Array
        (
            [0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
            [1] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
        )

    [tmp_name] => Array
        (
            [0] => /tmp/php2LK7xC
            [1] => /tmp/phpAKki0M
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 30887
            [1] => 30887
        )
)

我需要 output,如上面预期的 Output 所示。 请提供代码以获得解决方案!

这个方法用array_search保存name中找不到的key,以后用foreach删除

$a = ['detail12.docx', 'resume.docx'];
$b = [
    'name' => ['detail12.docx', 'document.pdf', 'resume.docx', 'test.php'],
    'type' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'test']
];
$keys = [];
foreach($b['name'] as $index => $value){
    if(array_search($value, $a) === false){
        $keys[] = $index;
    }
}
foreach($b as $index => $array){
    foreach($keys as $key){
        unset($b[$index][$key]);
    }
}
print_r($b);

Output:

Array
(
    [name] => Array
        (
            [0] => detail12.docx
            [2] => resume.docx
        )

    [type] => Array
        (
            [0] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
            [2] => application/vnd.openxmlformats-officedocument.wordprocessingml.document
        )

)

附言。 当然,我创建了一个包含一些条目的示例,作为视觉测试

参考:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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