将两个具有不同结构的PHP数组组合在一起,同时清除重复的记录

时间:2014-09-08 16:02:03

标签: php arrays

我有两个数组,下面是结构的例子:

数组#1 - 键存储在数组的第一个索引中作为相应的值。

Array(
    [0] => Array(
        [0] => name
        [1] => time
    ),
    [1] => Array(
        [0] => Bob
        [1] => 20
    ),
    [2] => Array(
        [0] => Jack
        [1] => 25
    )
)

数组#2 - 每个数组都有一个数字键和命名键,相应的值相同

Array(
    [0] => Array(
        [name] => Bob
        [0] => Bob
        [time] => 20
        [1] => 20
    ),
    [1] => Array(
        [name] => Test
        [0] => Test
        [time] => 40
        [1] => 40
    )
)

尝试:

foreach($arr as $record) {

    if(!in_array($record['name'], $names))
        $names[] = $record['name'];

}

foreach($csv as $rec) {

    if(!in_array($rec[0], $names))
        $names[] = $rec[0];

}

如何组合这些数组,并根据名称的值进行清除和复制?

1 个答案:

答案 0 :(得分:0)

尝试下面的代码,我在代码之间添加了命令。

//Array 1
$array1 = Array(
0 => Array(
    0 => "Bob",
    1 => 20,
),
1 => Array(
    0 => "Jack",
    1 => 25,
));

//Array 2
$array2 = Array(
0 => Array(
    "name" => "Bob",
    0 => "Bob",
    "time" => 20,
    1 => 20,
),
1 => Array(
    "name" => "Test",
    0 => "Test",
    "time" => 40,
    1 => 40,
));

//Function to search if the value already exists
function inArray($array, $search)
{
    foreach($array as $key=>$subArray)
    {
        if(in_array($search, $subArray))
        {
            return true;
        }
    }   

    return false;
}

$newArray = array();

//Loop over array1 length + array2 length   
for($i = 0 ; $i < (count($array1) + count($array2)) ; $i++)
{
    //Choose the array based on the counter ($i)
    if($i < count($array1))
    {
        $data       = $array1;
        $arrayIndex = $i;
    }
    else
    {
        $data       = $array2;
        $arrayIndex = $i - count($array1);
    }       

    //Check if array value exists
    if(!inArray($newArray,$data[$arrayIndex][0]))
    {
        //Add if it doesn't exists with the keys 'name' and 'time'
        $newArray[] = array('name' => $data[$arrayIndex][0], 'time'=> $data[$arrayIndex][1]);
    }       
}

print_r($newArray);

输出将是:

Array
(
    [0] => Array
        (
            [name] => Bob
            [time] => 20
        )

    [1] => Array
        (
            [name] => Jack
            [time] => 25
        )

    [2] => Array
        (
            [name] => Test
            [time] => 40
        )

)