PHP基于给定索引的匹配值合并数组[duplicate]

yws3nbqq  于 2022-12-21  发布在  PHP
关注(0)|答案(4)|浏览(110)
    • 此问题在此处已有答案**:

Merge arrays of associative arrays by shared column values(3个答案)
5个月前关闭。
我有两个这样的数组:

    • 数组1**
Array
(
    [0] => Array
        (
            [ID] => 101
            [Code] => 1075
            [Date] => 2012-03-03 17:13:12.433
        )

    [1] => Array
        (
            [ID] => 103
            [Code] => 175
            [Date] => 2012-09-05 20:30:02.217
        )

    [2] => Array
        (
            [ID] => 109
            [Code] => 178
            [Date] => 2012-07-05 20:30:02.217
        )

)
    • 数组2**
Array
(
    [0] => Array
        (
            [Amount] => 1234
            [ID] => 101
        )

    [1] => Array
        (
            [Amount] => 1342
            [ID] => 103
        )

    [2] => Array
        (
            [Amount] => 0
            [ID] => 0
        )

)

我使用这段代码根据ID索引的匹配值将它们组合起来。

$combined = array();
           foreach ($arr as $arrs) {
                   $comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');
                   foreach ($arr4 as $arr2) {
                       if ($arr2['ID'] == $arrs['ID']) {
                           $comb['Amount'] = $arr2['Amount'];
                           break;
                       }
                       else {
                        $comb['Amount'] = $arr2['Amount'];
                       }
                   }
               $combined[] = $comb;
           }
echo print_r($combined);

下面是我从这段代码中得到的预期输出:

Array
(
    [0] => Array
        (
            [ID] => 101
            [Code] => 1075
            [Date] => 2012-03-03 17:13:12.433
            [Amount] => 1234
        )

    [1] => Array
        (
            [ID] => 103
            [Code] => 175
            [Date] => 2012-09-05 20:30:02.217
            [Amount] => 1342
        )

    [2] => Array
        (
            [ID] => 109
            [Code] => 178
            [Date] => 2012-07-05 20:30:02.217
            [Amount] => 0
        )

)

我想优化代码,以便

$comb = array('ID' => $arrs['ID'], 'Code' => $arrs['Code'],'Date' => $arrs['Date'],'Amount' => '');

应该是动态生成的,而不是硬编码的。并且我希望代码自动将所有其他字段添加到ID匹配的第一个数组中,而不是$comb['Amount'] = $arr2['Amount'];
我如何实现这一目标?

pftdvrlh

pftdvrlh1#

最简单的解决方案,使它完全动态除了ID,做如下:

$arr2 = array_column($array2, "ID");

$finalArray = array();
foreach($array1 as $arr){
    $key = array_search($arr['ID'], $arr2);
    if($key ===false){
        $key = array_search(0, $arr2);
    }
    unset($array2[$key]['ID']);
    $finalArray[] =     array_merge($arr,$array2[$key]);
}

print_r($finalArray);

输出:-https://3v4l.org/1sDJs

2vuwiymt

2vuwiymt2#

首先使用ID作为密钥:

$arr1 = array_column($arr1, null, "ID");
$arr2 = array_column($arr2, null, "ID");

然后对键进行排序(要解决不相同的原始索引:

ksort($arr1);
ksort($arr2);

然后使用array_map作为:

$res = array_map('array_merge', $arr1, $arr2);

在末尾使用array_values可忽略ID键。
如果您有另一个包含ID字段的数组,您可以在它们上使用相同的逻辑-注意array_map可以获得2个以上的输入数组...
参考:array_columnarray_maparray_mergeksort
示例:3v4l

    • 编辑日期**:

使用模板修复元素缺失的问题:

$keys = array_merge(array_keys($a[0]), array_keys($b[0]));
$template = array_combine($keys, array_fill(0, count($keys), null)); // create array of null for all keys
$a = array_column($a, null, "ID");
$b = array_column($b, null, "ID");
ksort($a);
ksort($b);

$res = array_map(function ($e1, $e2) use ($template){
    if ($e1 && $e2) return array_merge($e1, $e2); // if exist merge
    $e = $e1 ? $e1 : $e2; //get the exist element
    return array_replace ($template, $e); // add it
}, $a, $b);

请注意,此解决方案将仅对2个阵列有效-它可以进行一般化,但我将其留给您
示例:3v4l

rjjhvcjd

rjjhvcjd3#

我调整你的代码做你需要的,这里是完整的代码,为我工作:

<?php

$arr=Array(
     Array("ID" => 101, "Code" => 1075, "Date" => "2012-03-03 17:13:12.433"),
    Array("ID" => 103, "Code" => 175, "Date" => "2013-03-03 17:13:12.433"),
    Array("ID" => 109, "Code" => 178, "Date" => "2014-03-03 17:13:12.433")
);

$arr4 = Array(
    Array("ID" => 101, "Amount" => 1234),
    Array("ID" => 103, "Amount" => 1342),
    Array("ID" => 0, "Amount" => 0)
);

$combined = array();

foreach ($arr as $i => $arrs) {
    $combined['ID'][$i] = $arrs['ID'];
    $combined['Code'][$i] = $arrs['Code'];
    $combined['Date'][$i] = $arrs['Date'];

    foreach ($arr4 as $arr2) {
        if ($arr2['ID'] == $arrs['ID']) {
            $combined['Amount'][$i] = $arr2['Amount'];
            break;
        }
    }

    if (!isset($combined['Amount'][$i])) {
        $combined['Amount'][] = 0;
    }

}

echo print_r($combined);

?>

如果你因为不同的原因需要进一步的操作,我建议你阅读关于array_keysarray_values方法的文章,它们很有帮助。

wi3ka0sx

wi3ka0sx4#

$firstArray = [
    [
        'ID' => 101,
        'Code' => 1075,
        'Date' => '2012-03-03 17:13:12.433',
    ],
    [
        'ID' => 103,
        'Code' => 175,
        'Date' => '2012-09-05 20:30:02.217',
    ],
    [
        'ID' => 109,
        'Code' => 178,
        'Date' => '2012-07-05 20:30:02.217',
    ],
];

$secondArray = [
    [
        'ID' => 101,
        'Amount' => 1234,
    ],
    [
        'ID' => 103,
        'Amount' => 1342,
    ],
    [
        'ID' => 0,
        'Amount' => 0,
    ],
];

class DTO implements \Serializable
{
    /** @var int */
    private $id;

    /** @var int */
    private $code;

    /** @var string */
    private $date;

    /** @var int */
    private $amount = 0;

    /**
     * {@inheritDoc}
     */
    public function serialize()
    {
        return [
            'ID' => $this->id,
            'Code' => $this->code,
            'Date' => $this->date,
            'Amount' => $this->amount,
        ];
    }

    /**
     * {@inheritDoc}
     *
     * @param array $serialized
     */
    public function unserialize($serialized): self
    {
        $this->id = $serialized['ID'];
        $this->code = $serialized['Code'];
        $this->date = $serialized['Date'];
        $this->amount = $serialized['Amount'] ?? 0;

        return $this;
    }
}

$thirdArray = [];
foreach ($secondArray as $item) {
    $id = $item['ID'];
    unset($item['ID']);
    $thirdArray[$id] = $item;
}

$thirdArrayKeys = array_keys($thirdArray);
foreach ($firstArray as &$item) {
    $id = $item['ID'];
    $dto = new DTO();
    $dto->unserialize($item);
    if (in_array($id, $thirdArrayKeys)) {
        $dto = $dto->unserialize(array_merge($item, $thirdArray[$id]));
    }

    $item = $dto->serialize();
}

http://sandbox.onlinephpfunctions.com/code/ee72a1c89782f4eef25a1143816f237ca6af129c

相关问题