【问题标题】:PHP merge array by keysPHP按键合并数组
【发布时间】:2014-03-02 16:58:11
【问题描述】:

我有 2 个数组。

商品数组和分隔符数组。

$goods = [
    [
        'good_id' => '1',
        'name' => 'Good 1',
    ],
    [
        'good_id' => '24',
        'name' => 'Good 24',
    ],
    [
        'good_id' => '335',
        'name' => 'Good 335',
    ],
    [
        'good_id' => '1986',
        'name' => 'Good 1986',
    ],
];

$separators = [
    [
        'id' => '1',
        'good_id' => '0',
        'name' => 'Separator 1',
    ],
    [
        'id' => '2',
        'good_id' => '0',
        'name' => 'Separator 2',
    ],
    [
        'id' => '3',
        'good_id' => '4',
        'name' => 'This separator should set after 4 good_id and before 5 good_id if exists',
    ],
    [
        'id' => '4',
        'good_id' => '47',
        'name' => 'This separator should set after 47 good_id and before 48 good_id if exists',
    ],
    [
        'id' => '5',
        'good_id' => '9999',
        'name' => 'This separator should set after 9999 good_id and before 10000 good_id if exists',
    ],
    [
        'id' => '6',
        'good_id' => '9999',
        'name' => 'This separator should set after 9999 good_id and AFTER prevously separator AND before 10000 good_id if exists',
    ]

];

我需要通过 good_id 合并这些数组。 Spearators good_id 应该在good_id 之后设置good_id。

$merged = [
    [
        'id' => '1',
        'good_id' => '0',
        'name' => 'Separator 1',
    ],
    [
        'id' => '2',
        'good_id' => '0',
        'name' => 'Separator 2',
    ],
    [
        'good_id' => '1',
        'name' => 'Good 1',
    ],
    [
        'id' => '3',
        'good_id' => '4',
        'name' => 'This separator should set after 4 good_id and before 5 good_id if exists',
    ],
    [
        'good_id' => '24',
        'name' => 'Good 24',
    ],
    [
        'id' => '4',
        'good_id' => '47',
        'name' => 'This separator should set after 47 good_id and before 48 good_id if exists',
    ],
    [
        'good_id' => '335',
        'name' => 'Good 335',
    ],
    [
        'good_id' => '1986',
        'name' => 'Good 1986',
    ],
    [
        'id' => '5',
        'good_id' => '9999',
        'name' => 'This separator should set after 9999 good_id and before 10000 good_id if exists',
    ],
    [
        'id' => '6',
        'good_id' => '9999',
        'name' => 'This separator should set after 9999 good_id and AFTER prevously separator AND before 10000 good_id if exists',
    ]

];

【问题讨论】:

    标签: php merge


    【解决方案1】:

    据我了解,您需要合并两个数组并按good_id 子键对结果进行排序。假设这些数组没有具有相同 good_id 键的记录,您可以使用这个简单的解决方案:

    $merged = array_merge($goods, $separators);
    usort($merged, function ($a, $b) {
        return $a['good_id'] < $b['good_id']? -1 : 1;
    });
    

    【讨论】:

    • usort 不返回数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2022-06-14
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 2011-12-19
    相关资源
    最近更新 更多