0

嗨,请运行我的代码:

<?php
$arrayA=array(array("id" => 8, "name" => "test1"),  
            array("id" => 4, "name" => "test2"),  
            array("id" => 4, "name" => "test3")  
);
$arrayB=array(array("id" => 3, "domain_name" => "www.test.com","activation_key" =>"ADKLJ"),
            array("id" => 4,  "domain_name" => "www.yahoomail.com","activation_key" =>"LKLJ"),
            array("id" => 4, "domain_name" => "www.gmail.com","activation_key" =>"OLOLJ")           
);

//$places=Array();
$i=0;
foreach($arrayA as $itemA)
{
    $match=0;

    foreach($arrayB as $itemB)
    {
        if($itemA["id"]==$itemB["id"])
        {
            $arrayA[$i]["domain_name"]=$itemB["domain_name"];
            $arrayA[$i]["activation_key"]=$itemB["activation_key"];
            $match=1;
        }
    }
    if($match==0)
    {
            $arrayA[$i]["domain_name"]="";
            $arrayA[$i]["activation_key"]="";
    }
    $i++;
}
echo "<pre>";
print_r($arrayA);
echo "</pre>";

?>

输出

Array
(
    [0] => Array
        (
            [id] => 8
            [name] => test1
            [domain_name] => 
            [activation_key] => 
        )

    [1] => Array
        (
            [id] => 4
            [name] => test2
            [domain_name] => www.gmail.com
            [activation_key] => OLOLJ
        )

    [2] => Array
        (
            [id] => 4
            [name] => test3
            [domain_name] => www.gmail.com
            [activation_key] => OLOLJ
        )
)

但我的预期输出是

Array
(
    [0] => Array
        (
            [id] => 8
            [name] => test1
            [domain_name] => 
            [activation_key] => 
        )

    [1] => Array
        (
            [id] => 4
            [name] => test2
            [domain_name] => www.yahoomail.com
            [activation_key] => LKLJ
        )

    [2] => Array
        (
            [id] => 4
            [name] => test3
            [domain_name] => www.gmail.com
            [activation_key] => OLOLJ
        )
)
4

1 回答 1

0

您删除数组内容的条件应该在 Foreach 内:

//$places=Array();
$i=0;
$addedDomains = array();
foreach($arrayA as $itemA)
{
    $match=0;

    foreach($arrayB as $itemB)
    {
        if($itemA["id"]==$itemB["id"])
        {
            if(!in_array( $itemB["domain_name"], $addedDomains)){
                $arrayA[$i]["domain_name"]=$itemB["domain_name"];
                $arrayA[$i]["activation_key"]=$itemB["activation_key"];

                $addedDomains[] = $itemB["domain_name"];
            }
        }
        //if it doesnt match (you dont need the flag)
        else{
            $arrayA[$i]["domain_name"]="";
            $arrayA[$i]["activation_key"]="";
        }
    }

    $i++;
}

无论如何,我会看看 PHP 函数,例如:array_intersect

于 2012-12-13T10:10:57.893 回答