[英]Combining and Adding Array Values in PHP
我有一個這樣的數組結構:
Array
(
[0] => Array
(
[0] => cmi.interactions.0.result
[1] => 1
[2] => 0
)
[1] => Array
(
[0] => cmi.interactions.0.result
[1] => 0
[2] => 1
)
[2] => Array
(
[0] => cmi.interactions.0.result
[1] => 0
[2] => 1
)
[3] => Array
(
[0] => cmi.interactions.1.result
[1] => 1
[2] => 0
)
[4] => Array
(
[0] => cmi.interactions.1.result
[1] => 1
[2] => 0
)
[5] => Array
(
[0] => cmi.interactions.1.result
[1] => 1
[2] => 0
)
)
我想要的是以下內容:
Array
(
[0] => Array
(
[0] => cmi.interactions.0.result
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => cmi.interactions.1.result
[1] => 3
[2] => 0
)
)
基本上我想知道如何找到每個子數組中第一個值的匹配位置,並相應地添加第二個和第三個值?
像這樣的東西,沒有檢查
$out = array();
foreach($arr as $el)
if (!isset($out[$el[0]]))
$out[$el[0]] = $el;
else
for($i = 1; $i < count($el); $i++)
$out[$el[0]][$i] += $el[$i];
之后,您可以刪除鍵,例如$out = array_values($out);
對於這種情況,可以使用以下算法:
以下是對該算法的提示。 我沒有對其進行測試,因此,它可能無法完全正常工作。 但這應該給您一個很好的提示進行下去。
$prevValue="";
$sum1=0;
$sum2=0;
$index=0;
foreach ($arr as $value) {
if($prevValue==$value[0])
{
if(value[1]==1)
$sum1++;
if(value[2]==1)
$sum2++;
}else{
$ansArr[$index]=array($value[0], $sum1,$sum2);
}
$prevValue=$value[0];
}
你去。 我們將第二個數組構建為$ a2,並向其中添加元素,然后將總和累加到其中。 對您的值進行測試,確定。
function parse($a)
{
$a2 = array();
for ($i = 0; $i < sizeof($a); $i++) {
$isFound = false;
for ($i2 = 0; $i2 < sizeof($a2); $i2++) {
if ($a[$i][0] == $a2[$i2][0]) {
// We've already run into this search value before
// So add the the elements
$isFound = true;
$a2[$i2][1] += $a[$i][1];
$a2[$i2][2] += $a[$i][2];
break;
}
}
if (!$isFound) {
// No matches yet
// We need to add this one to the array
$a2[] = $a[$i];
}
}
return $a2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.