php – 合并和区分数组数组以查找常用值

前端之家收集整理的这篇文章主要介绍了php – 合并和区分数组数组以查找常用值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图循环几个数据库表结构并确定公共结构(即哪些列是相同的).最终结构应该只显示公共列,因此如果任何表具有唯一列,则它不应该在最终数组中.

这是三个表结构可能看起来像的示例.

$arr1 = [
    ["name"=>"col1","type"=>"varchar"],["name"=>"col2","type"=>"int"]    
];
$arr2 = [
    ["name"=>"col1","type"=>"int"],["name"=>"col3","type"=>"date"]    
];
$arr3 = [
    ["name"=>"col1","type"=>"int"]    
];

$arrays = [$arr1,$arr2,$arr3];

使用array_merge,array_diff,array_intersect或循环,是否可以确定哪些列对所有表都是通用的?

最终值应该是
[[“name”=>“col1”,“type”=>“varchar”]]

您可以将自定义比较方法array_uintersect()一起使用:
$arr1 = [
    ["name" => "col1","type" => "varchar"],["name" => "col2","type" => "int"]
];
$arr2 = [
    ["name" => "col1","type" => "int"],["name" => "col3","type" => "date"]
];
$arr3 = [
    ["name" => "col1","type" => "int"]
];

$common_columns = array_uintersect($arr1,$arr3,'compareDeepValue');

print_r($common_columns);

function compareDeepValue($val1,$val2)
{
    return (strcasecmp(serialize($val1),serialize($val2))) ;
}

输出

Array
(
    [0] => Array
        (
            [name] => col1
            [type] => varchar
        )

)

注意:

@Abracadaver提出了一个很好的观点,只有当数组约定的顺序相同时,此方法才能正常工作.

比你可以用例如:

function compareDeepValue($val1,$val2)
{
    return ($val1['name'] === $val2['name'] && $val1['type'] === $val2['type']) ? 0 : -1;
}
原文链接:https://www.f2er.com/php/137219.html

猜你在找的PHP相关文章