我有一组值会定期更新。更新阵列时,我想使用更新后的数组中的新值执行操作。
$old_node->field_name[0]['value'] = 'red'
$old_node->field_name[1]['value'] = 'yellow'
$old_node->field_name[2]['value'] = 'blue'
$updated_node->field_name[0]['value'] = 'green',
$updated_node->field_name[1]['value'] = 'red',
$updated_node->field_name[2]['value'] ='purple',
$updated_node->field_name[3]['value'] = 'blue',
因此'green'和'purple'的值是新数组中的新值。我需要通过函数运行ADDED中的每个值到新数组。类似的东西:
foreach(of the newly added values that are in the new array){
//do stuff;
}
更新阵列时可能会删除某些值,因此key =>值对可能会更改。
我试过了:
foreach($updated_node->field_name as $new_value){
if(!in_array($new_value['value'], $old_node->field_name) && $new_value['value'] !== NULL){
//Do stuff;
}
}
但这不起作用。我也尝试使用array_diff和array_intersect选择新值,但这也不起作用。
答案 0 :(得分:1)
$old_array = array(
0 => 'red',
1 =>'yellow',
2 => 'blue'
);
$new_array = array(
0 => 'green',
1 => 'red',
2 =>'purple',
4 => 'blue'
);
$diff = array_diff($new_array, $old_array);
print_r($diff);
/*
Array
(
[0] => green
[2] => purple
)
*/
获取新代码
$old_node->field_name[0]['value'] = 'red';
$old_node->field_name[1]['value'] = 'yellow';
$old_node->field_name[2]['value'] = 'blue';
$updated_node->field_name[0]['value'] = 'green';
$updated_node->field_name[1]['value'] = 'red';
$updated_node->field_name[2]['value'] = 'purple';
$updated_node->field_name[3]['value'] = 'blue';
$diff = array();
foreach($updated_node->field_name as $num => $field){
$tmpval = false;
foreach($old_node->field_name as $old){
if($field['value'] == $old['value']){
$tmpval = true;
}
}
if(!$tmpval){
$diff[$num] = $field['value'];
}
}
print_r($diff);
/*
Array
(
[0] => green
[2] => purple
)
*/
答案 1 :(得分:0)
$old_array = array(
[0] => 'red',
[1] =>'yellow',
[2] => 'blue',
);
$new_array = array(
[0] => 'green',
[1] => 'red',
[2] =>'purple',
[4] => 'blue',
);
$diff = array_diff($new_array, $old_array);
var_dump($diff);
导致
array(2) {
[0]=>
string(5) "green"
[2]=>
string(6) "purple"
}
这是正确的(预期)结果。
答案 2 :(得分:0)
这是一个简单函数,用于加载两个带有添加和删除值的数组:
function loadArrayDifferences($before, $after, &$added, &$removed) {
$added = array_diff($after, $before);
$removed = array_diff($before, $after);
}
这是一个测试脚本:
<?php
$ar1 = array(
'one',
'two',
'three',
'four'
);
$ar2 = array(
'two',
'four',
'six',
'eight',
);
$adds = array();
$rems = array();
loadArrayDifferences($ar1, $ar2, $adds, $rems);
var_dump($adds);
var_dump($rems);
function loadArrayDifferences($before, $after, &$added, &$removed) {
$added = array_diff($after, $before);
$removed = array_diff($before, $after);
}
输出:
array(2) {
[2]=>
string(3) "six"
[3]=>
string(5) "eight"
}
array(2) {
[0]=>
string(3) "one"
[2]=>
string(5) "three"
}