Display values from one associative array whose key exists as the value in another array

醉酒当歌 提交于 2019-12-11 08:27:49

问题


I have two arrays, one is "OperID" the other is "OperSums". The OperID array contains ID numbers, and the OperSums array contains IDs attached to a total which looks like this:

Array 1 (OperID)

{[0] => oper1 [1] => oper2 [2] => 3 [3] => oper4 [4] => oper5 [5] => oper6 [6] => oper7 [7] => oper8 [8] => oper9}

Array 2 (OperSums)

{["oper3"]=> float(17498.5) ["oper1"]=> float(10383.5) ["oper2"]=> float(6277) ["oper4"]=> float(10224.67) ["oper6"]=> float(3955.65) ["oper5"]=> float(4997.78) ["oper8"]=> float(11382) ["oper9"]=> float(5072.1) ["oper7"]=> float(14759) ["oper-nb3n0hah-1tueubqo"]=> float(1033.45) ["oper-50f6e4ad-9effbec7"]=> float(3058) ["oper-4f05a90b-03b379f9"]=> float(12112.5) ["oper-4db82d0b-796a3081"]=> float(621) ["oper-qxr9ryex-bsmm0g6f"]=> string(4) "0.00" ["oper-qtgjvw8y-1uqtw058"]=> float(10023) ["oper-487b885e-dbbae536"]=> string(6) "340.00" ["oper-shcuaee2-yldfdxsd"]=> float(467) ["oper-416fd551-da6937eb"]=> float(6563) ["oper-50564d75-f1da98ec"]=> string(4) "0.00" ["oper-l65tf5ex-w5qfinca"]=> float(1746) ["oper-52657816-3d6516e2"]=> float(3495) ["oper-4a82c3be-bccc185d"]=> float(0) ["oper-1f2mnwry-nfywuasi"]=> string(6) "255.95"}

I'm wanting to gather only the operator values that are in both arrays and display the totals for each operator which are within each float in Array 2, and truncate all extra data. I'm really not that great with associative arrays, so any pointers or tips in the right direction would be greatly appreciated. This is in PHP by the way.

Here is the code I'm working with so far:

$operSums = array();

$operearnedArray[] = array(
      'amount' => $row['ChargeAmount'], 
      'id' => $row['OperatorID']);


foreach ($operearnedArray as $value) {
      if($value['id'] == '' || $value['id'] == null) {
      continue;
      }
      if(array_key_exists($value['id'], $operSums)) {
        $operSums[$value['id']] += $value['amount'];
      } else {
        $operSums[$value['id']] = $value['amount'];
      }
}

回答1:


If I understand correctly, you just need to step through $OperSums (Array 2) and display the value if the key exists in $OperID (Array 1)?

foreach ($OperSums as $id => $value) {
    if (in_array($id,$OperID)) {
        echo $id.' => '.$value;
    }
}

If you actually need to "truncate all extra data" then unset the arrays as you go (or create a new array), although that does not seem necessary if you are just displaying the results?



来源:https://stackoverflow.com/questions/26664907/display-values-from-one-associative-array-whose-key-exists-as-the-value-in-anoth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!