首页 > 解决方案 > 用于比较和合并值的 PHP Array 函数

问题描述

感谢您的时间!

在查看了几个“比较和合并”线程之后,最后,我将请求某人帮助解决这个非常具体的场景。

$input = array(
  [ 2616 ] => array(
    [ 9878767654 ] => array(
      [ 987987987 ] => 987987987, 
      [ 987987986 ] => 987987986,
    ),
  ), 
  [ 2618 ] => array(
    [ 9878767654 ] => array(
      [ 987987987 ] => 987987987,
    ),

  ), 
  [ 'tmp-9878767654' ] => array(
    [ 9878767654 ] => array(
      [ 987987985 ] => 987987985, 
      [ 987987987 ] => 987987987,
    ),

  ), 
  [ 'tmp-9878767655' ] => array(
    [ 9878767655 ] => array(
      [ 987987975 ] => 987987975,
    ),
  ),
);

$desired_output = array(
  [ 2616 ] => array(
    [ 9878767654 ] => array(
      [ 987987987 ] => 987987987, 
      [ 987987986 ] => 987987986,
      [ 987987985 ] => 987987985,
    ),
  ),
  [ 2618 ] => array(
    [ 9878767654 ] => array(
      [ 987987987 ] => 987987987, 
      [ 987987986 ] => 987987986,
      [ 987987985 ] => 987987985,
    ),
  ),
  [ 'tmp-9878767655' ] => array(
    [ 9878767655 ] => array(
      [ 987987975 ] => 987987975,
    ),
  ),
);

这是按商店 ID 列出的产品库存(按产品 ID 和型号 ID 列出)。我想合并模型 ID 值,其中产品 ID 与存储 ID 以“tmp-”开头的数组相同。如果产品 ID 不匹配,那么我希望该数组保持原样。我希望我有点道理。

请帮忙。

标签: phparraysmergecompare

解决方案


这是解决您的示例提出的特定问题的代码段:

$temporaryStores = [];
$prefix = 'tmp-';
$prefixLength = strlen($prefix);

// extract the temporary store structures
foreach ($input as $storeId => $store) {
    if (is_string($storeId) && strpos($storeId, $prefix) === 0) {
        $productId = (int) substr($storeId, $prefixLength);
        $temporaryStores[$productId] = $store;
        unset($input[$storeId]);
    }
}

// merge matching temporary store structures into the actual ones
$mergedProductIds = [];
foreach ($temporaryStores as $temporaryProductId => $temporaryModels) {
    $temporaryModels = reset($temporaryModels); // Incompatible array structure
    foreach ($input as $storeId => $store) {
        foreach ($store as $productId => $models) {
            if ($productId === $temporaryProductId) {
                $modelsIds = array_merge($temporaryModels, $models);
                $modelsIds = array_unique($modelsIds);
                $input[$storeId][$productId] = $modelsIds;
                $mergedProductIds[] = $temporaryProductId;
                unset($temporaryStores[$temporaryProductId]);
            }
        }
    }
}

// append leftover temporary store structures to the result
foreach ($temporaryStores as $temporaryProductId => $temporaryModels) {
    if (!in_array($temporaryProductId, $mergedProductIds, true)) {
        $input[$prefix . $temporaryProductId] = $temporaryModels;
    }
}

var_dump($input);

此代码段可能对您有用,也可能不适用。无论哪种方式,我强烈建议您将此代码重构为使用更面向对象的设计。每个值/结构代表什么很明显,并且验证可以单独进行。

现在您不得不处理不兼容的数组结构,这些结构在视觉上看起来像是一团难以理解的混乱。


推荐阅读