PHP数组:条件和

时间:2019-01-02 13:52:25

标签: php arrays calculation

我有一个看起来像这样的数组:

$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);

当只考虑第一个字符时,我想对每个“唯一”键的值求和。结果应为:

$newarray = array("a" => 3, "b" => 5);

我已经尝试过在另一个foreach()循环中使用foreach()循环,如下所示:

foreach ($xml->children() as $output) {
  foreach ($array as $key => $value) {
    if (substr($key,0,1) == $output->KEY) {
      $sum += $value; echo $sum;
    }
  }
}

它没有用,因为结果显然添加了先前的计算。

5 个答案:

答案 0 :(得分:2)

简单的解决方案:

$final_array=[];
foreach($array as $key=>$value){
     $final_array[$key[0]] =  (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
 }
 print_r($final_array);

输出:-https://3v4l.org/tZ4Ei

答案 1 :(得分:1)

一个简单的import { Injectable } from '@angular/core'; declare var $: any; @Injectable({ providedIn: 'root' }) export class FroalaService { constructor() { } public initFroala(): void { $.FroalaEditor.DefineIcon('insertnonbreakingspace', {NAME: 'arrows-h'}); $.FroalaEditor.RegisterCommand('insertnonbreakingspace', { title: 'Non-Breaking Space', focus: true, undo: true, refreshAfterCallback: true, callback: function () { this.html.insert('<span style="white-space: nowrap;"> </span>'); } }); $.FroalaEditor.RegisterShortcut(32, 'insertnonbreakingspace', null, 'Space', false, false); } } 应该可以做到:

isset

答案 2 :(得分:1)

您可以尝试这个。它会从您的密钥中提取第一个字母,并使用该第一个字母密钥对所有值求和。

$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
$result = array();
foreach ($array as $oldkey => $val) {
    $newkey = substr($oldkey, 0, 1);
    if (isset($result[$newkey]) === false)
        $result[$newkey] = $val;
    else
        $result[$newkey] += $val;
}
var_dump($result);

答案 3 :(得分:1)

尝试这种方式

$array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
$result = array();
foreach($array as $key => $value){
    if(isset($result[$key[0]])){
        $result[$key[0]] = $result[$key[0]]+$value;
    } else {
        $result[$key[0]] = $value;
    }
}
print_r($result);

答案 4 :(得分:0)

快速简便,您可以在字符后面的数组中包含任意数量的数字。

<?php

$array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
$newArray = [];

foreach ($array as $key => $value) {
  $key = preg_replace("/[0-9]*$/", "", $key);
  $newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
}

print_r($newArray);