我有2个数组如下:
array(2) { ["2018-05"]=> string(2) "15" ["2018-06"]=> string(3) "100" }
array(1) { ["2018-05"]=> string(1) "5" }
我希望进行计算以找出差异,以便返回:
array(2) { ["2018-05"]=> string(2) "10" ["2018-06"]=> string(3) "100" }
由于这是一个多维数组,我不知道如何显示"年 - 月"作为数组键,有人可以赐教吗?
感谢。
答案 0 :(得分:1)
试试此代码
$a = ["2018-05"=> "15", "2018-06"=> "100" ];
$b = ["2018-05"=> "5"];
$c = $a;
foreach($b as $k=> $i){
if(array_key_exists($k,$c)){
$c[$k] = $a[$k] - $b[$k];
}
else{
$c[$k] = 0-$i;
}
}
答案 1 :(得分:0)
假设您不想考虑相同的值而您想要绝对值,那么这应该有效
// Send a message containing the page details back to the event page
// Add bubble to the top of the page.
var bubbleDOM = document.createElement('div');
bubbleDOM.setAttribute('class', 'selection_bubble');
document.body.appendChild(bubbleDOM);
var token = null;
function init(event) {
var topic = '';
if (window.getSelection) {
topic = window.getSelection().toString();
} else if (document.selection) {
topic = document.selection.createRange().topic;
} else {
return topic;
}
chrome.runtime.sendMessage(
{ message: 'getToken', key: 'user_token' },
function(response) {}
);
if (topic.length > 0) {
renderBubble(event, topic);
chrome.runtime.sendMessage({ message: 'setTopic', data: topic }, function(
response
) {});
}
}
document.addEventListener('click', init);
// Move that bubble to the appropriate location.
function renderBubble(event, selection) {
bubbleDOM.innerHTML = `<p class="topic" id="topic-crm">${selection}</p>`;
document.getElementById('topic-crm').addEventListener('click', function() {
topicCrm(selection);
});
}
function topicCrm(topic) {
if (topic) {
chrome.runtime.sendMessage({ message: 'topicCrm', data: topic }, function(
response
) { console.log('response', response); // gives undefined });
}
}
如果您希望保留$els[]["2018-05"]="15";
$els[]["2018-06"]="100";
$els[]["2018-05"]="5" ;
$els[]["2018-05"]="1" ;//added
$els[]["2018-06"]="50";//added
$newEls = [];
foreach($els as $key => $el){
$newEls[key($el)] = $el[key($el)];
foreach($els as $key2 => $el2){
if(key($els[$key]) == key($els[$key2]) && $els[$key][key($els[$key])] != $els[$key2][key($els[$key2])]){
$newEls[key($el)] = abs($els[$key][key($els[$key])] - $els[$key2][key($els[$key2])]);
}
}
}
echo "<pre>";print_r($newEls);
和[0]["2018-05"]="15"
等相同的值,则需要采用其他方法。因为最好的方法可能是使用队列。
答案 2 :(得分:0)
<?php
$a = ['2018-05'=> '15', '2018-06'=> '100'];
$b = ['2018-05'=> '5'];
$years = array_map(NULL, $a, $b);
$years = array_combine(array_keys($a), $years);
$differences = array_map(function ($year_diffs) : float {
// Did we get a pair to compare?
$has_diff = isset($year_diffs[0]) and isset($year_diffs[1]);
// If we got a pair then compare, else assume we got one.
$diff = $has_diff ? abs($year_diffs[0] - $year_diffs[1]) : $year_diffs[0];
return $diff;
}, $years);
var_dump($differences);
我不得不承担一些事情
我觉得无论您的系统是什么,都可能违反上述标准,但您需要为不同的解决方案提供更多背景信息