【问题标题】:Compare 2 arrays and retrieve the differences using PHP比较 2 个数组并使用 PHP 检索差异
【发布时间】:2014-06-15 14:56:14
【问题描述】:

我不是 PHP 专家,但我正在尝试在 PHP 中比较 2 个数组(数据库关系和架构),我需要检索这 2 个数组之间的差异,我正在使用这个 php 代码

    <?php

function maxEntities($rela, $db){
    $maxenty = array();
    $found   = false;

     foreach ($rela as $valor1) {  
      print $valor1[0] . " |  ";
    }

    print " <br \>";
     foreach ($db as $valor2) {

      print  $valor2[0] . " |  ";
    }
 $maxenty = array_diff($rela[0], $db[0]);

    print " <br \> <br \>";

    foreach ($maxenty as $valor) {

      print "  " . $valor;
    }
}

这段代码给了我这个输出

 Sale | Customer | Sale_Fee | Sale | Location | Sale | Sale | Sale_Iten | Product | Customer | Location | Sale_Iten | Sale_Fee | Region | 
Customer | Customer_Type | Fee_Type | Location | Location_Type | Period | Product | Product_Type | Region | Sale | Sale_Fee | Sale_Iten | State | 

Sale Customer_Cust_Id 

我期望的输出是

期间、客户类型、状态、位置类型、产品类型和费用类型

我该如何解决我的问题?

我也试过foreach,但也给我一个错误的输出

 foreach ($rela as $relaV) {
        foreach ($db as $dbV) {

            if ($dbV[0] == $relaV[0]) {
                $found = true;
            }
            if (!$found) {
                $found   = false;
               $maxenty[] = $dbV[0];  
            } 
        }
    }

在这种情况下,我的输出是

Customer
Customer_Type
Fee_Type
Location
Location_Type
Period
Product
Product_Type
Region

客户、地区、位置在两个数组中

【问题讨论】:

  • 向我们展示数组本身的样本。

标签: php arrays


【解决方案1】:

您的数组的结构不是很清楚。到目前为止,从您的代码中我猜出以下结构:

$rela = array(array('Sale'), array('Customer'), array('Sale_Fee'), array('Sale'), array('Location'), array('Sale'), array('Sale'), array('Sale_Iten'), array('Product'), array('Customer'), array('Location'), array('Sale_Iten'), array('Sale_Fee'), array('Region'));
$db = array(array('Customer'), array('Customer_Type'), array('Fee_Type'), array('Location'), array('Location_Type'), array('Period'), array('Product'), array('Product_Type'), array('Region'), array('Sale'), array('Sale_Fee'), array('Sale_Iten'), array('State'));

如果这是您的数组的结构,那么您可以使用以下代码来获取差异(从您的 foreach-approach 采用,可能还有其他方法):

$maxenty = array();
foreach ($db as $dbValue) {
    $found = false;
    foreach ($rela as $relaValue) {
        if ($relaValue[0] == $dbValue[0]) {
            $found = true;
            break;
        }
    }
    if (!$found) {
        $maxenty[] = $dbValue[0];
    }
}

print_r($maxenty);

这将为您提供$maxenty,如下所示:

Array
(
    [0] => Customer_Type
    [1] => Fee_Type
    [2] => Location_Type
    [3] => Period
    [4] => Product_Type
    [5] => State
)

【讨论】:

    猜你喜欢
    • 2015-08-21
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2014-07-15
    • 2020-02-15
    相关资源
    最近更新 更多