Php 基于id合并数组数据
原始数据Php 基于id合并数组数据,php,Php,原始数据 Array ( [0] => Array ( [bet_id] => 7 [agent_id] => 2 [bet_type] => 1 [amount] => 0 [name] => ethan ) [1] => Array ( [bet_id] => 7
Array
(
[0] => Array
(
[bet_id] => 7
[agent_id] => 2
[bet_type] => 1
[amount] => 0
[name] => ethan
)
[1] => Array
(
[bet_id] => 7
[agent_id] => 2
[bet_type] => 3
[amount] => 0
[name] => ethan
)
[2] => Array
(
[bet_id] => 7
[agent_id] => 4
[bet_type] => 1
[amount] => 2
[name] => alex
)
[3] => Array
(
[bet_id] => 7
[agent_id] => 4
[bet_type] => 4
[amount] => 100
[name] => alex
)
)
我陷入了将上述数据分离的逻辑思维。上面的数组将循环所有用户数据,这里有2个用户。如何基于agentId将其合并为2个数组。它将变成如下所示
Array
(
[0] => Array
(
[agent_id] => 2
[name] => ethan
[1] => 2 //bettype & amount
[3] => 0 //bettype & amount
[bet_id] => 7
)
[1] => Array
(
[agent_id] => 4
[name] => alex
[1] => 0 //bettype & amount
[4] => 100 //bettype & amount
[bet_id] => 7
)
)
注意:唯一不同的数据是代理id、下注类型和金额。其他数据将是相同的。将
bet\u type
作为键,将amount
作为值,会使数据结构看起来很糟糕,但让我们来创建它
$result = [];
foreach($data as $user) {
$found = -1;
for($i = 0; $i<count($result); $i++) {
if($result[$i]["agent_id"] == $user["agent_id"]) {
$found = $i;
break;
}
}
// if not found, create new
if($found == -1) {
$result[] = [
"agent_id" => $user["agent_id"],
"name" => $user["name"],
"bet_id" => $user["bet_id"],
$user["bet_type"] => $user["amount"]
];
} else {
$result[$i][$user["bet_type"]] = $user["amount"];
}
}
我建议你改变bet\u type
的位置,把它们放在子数组中,如下所示
Array
(
[0] => Array
(
[agent_id] => 2
[name] => ethan
[bet_id] => 7
[1] => 0
[3] => 0
)
[1] => Array
(
[agent_id] => 4
[name] => alex
[bet_id] => 7
[1] => 2
[4] => 100
)
)
$result = [];
foreach($data as $user) {
$found = -1;
for($i = 0; $i<count($result); $i++) {
if($result[$i]["agent_id"] == $user["agent_id"]) {
$found = $i;
break;
}
}
// if not found, create new
if($found == -1) {
$result[] = [
"agent_id" => $user["agent_id"],
"name" => $user["name"],
"bet_id" => $user["bet_id"],
"details" => [
$user["bet_type"] => $user["amount"]
]
];
} else {
$result[$i]["details"][$user["bet_type"]] = $user["amount"];
}
}
(
[0] => Array
(
[agent_id] => 2
[name] => ethan
[bet_id] => 7
[details] => Array
(
[1] => 0
[3] => 0
)
)
[1] => Array
(
[agent_id] => 4
[name] => alex
[bet_id] => 7
[details] => Array
(
[1] => 2
[4] => 100
)
)
)
您是否尝试过使用常用的foreach?您确定使用下注类型作为键,使用金额作为值是一个好的解决方案吗?呃,仍然在考虑更好的方法,但遇到了以下问题:(.@MMMM欢迎来到Stack Overflow。请学习Stack Overflow的工作原理,并阅读如何提高问题的质量。然后,您的问题将包括您作为一个可由其他人编译和测试的源代码。请参阅:。向我们展示您尝试过的源代码,并解释它们是如何失败的。