php - 用于比较和合并值的 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 不匹配,那么我希望该数组保持原样。我希望我有点道理。
请帮忙。
解决方案
这是解决您的示例提出的特定问题的代码段:
$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);
此代码段可能对您有用,也可能不适用。无论哪种方式,我强烈建议您将此代码重构为使用更面向对象的设计。每个值/结构代表什么很明显,并且验证可以单独进行。
现在您不得不处理不兼容的数组结构,这些结构在视觉上看起来像是一团难以理解的混乱。
推荐阅读
- visual-studio-code - 是否可以仅在保存文件时(而不是在编辑期间)刷新大纲视图?
- python - 如何根据最终值和倒数第二个值为整数变量编写“if/unless”语句?
- sql - 根据日期将行转换为列以比较销售与促销
- java - 如何在此界面中覆盖此方法(请参阅代码)?
- nginx - 在 Nginx 反向代理后面带有 Wildfly 应用程序的 Keycloak
- php - 添加后退按钮
- knex.js - 我们如何创建关系,但不允许更新其中一个表?以及 insertWithRelated 与 upsertGraph 之间的区别
- python-2.7 - 使用 networkx 和 matplotlib 为图中的节点分配多个单词
- c# - 如何使用协程(或任何其他方法)在点击时在屏幕上滑动精灵?
- python - 将多个列值合并为一列以在python pandas中重复行