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 に答える