问题描述
如果该值大于特定数据,如何减去该值?
How can I subtract the value of an array if that value is greater than specific data?
例如:
我有一个数组菜单位置的位置 [0,3,10,5,6,9,2,7,1,4,8,11]
我想减去所有较大的值比 selectedDeletedNumbers
保持位置。
I have an array of menu's position [0,3,10,5,6,9,2,7,1,4,8,11]
I want to subtract all values that are greater than selectedDeletedNumbers
and stay in their position.
示例:如果我删除了 3
和 5
。 我正在使用复选框删除
Example: If I delete 3
and 5
. I am using checkbox to delete
输出应该是这样的。
[ 0,8,4,7,2,5,1,3,6,9]
大于 3
减去 1
,大于 5
减去 2
,因为我选择了 2
个数字。
Greater than 3
is subtract by 1
, and greater than 5
is subtract by 2
since I selected 2
numbers.
HTML
@foreach ($columns as $key => $column)
<div class="checkbox checkbox-danger col-xs-6 el{{ $column->Field }}">
<input type="checkbox" name="CheckboxDelete[]" id="check{{ $column->Field }}" data-column="{{ $key }}" value="{{ $column->Field }}">
<label for="check{{ $column->Field }}"><b style="color: grey">{{ strtoupper($column->Field) }}</b></label>
</div>
@endforeach
这是我的代码,但仅在被删除1时才可用
Here is my code, but it's only when deleted 1, and not in a position as well.
$searchArr = array_search( $selectedDeletedNumbers, $items);
unset($items[$searchArr]);
$numbers = [];
foreach ($items as $item) {
if ($item > $col[1])
$numbers[] = $item - 1;
}
谢谢。
推荐答案
为简洁起见,我将您的输入数据称为:
For clarity and brevity, I'll refer to your input data as:
$array = [0, 3, 10, 5, 6, 9, 2, 7, 1, 4, 8, 11];
$deletes = [3, 5];
我的两个摘要都不需要进行排序或准备。
There is no sorting or preparation required for either of my snippets.
以下两项的输出是:
array (
0 => 0,
1 => 8,
2 => 4,
3 => 7,
4 => 2,
5 => 5,
6 => 1,
7 => 3,
8 => 6,
9 => 9,
)
大多数基于函数的方法:()
Mostly function based approach: (Demo)
foreach (array_diff($array, $deletes) as $value) {
$result[] = array_reduce(
$deletes,
function ($carry, $item) use ($value) {
return $carry - ($value > $item);
},
$value
);
}
var_export($result);
*注:($ value> $ item)$ c当用于算术运算时,$ c>将被评估为
true
或 false
, true
= 1
和 false
= 0
。
*note: ($value > $item)
will evaluated as true
or false
, when used in arithmetic, true
= 1
and false
= 0
.
基于语言构造的方法:()
Language construct based approach: (Demo)
foreach ($array as $value) {
foreach ($deletes as $delete) {
if ($value == $delete) {
continue 2; // goto next value in outer loop without pushing
}
if ($value > $delete) {
--$value; // decrement value
}
}
$result[] = $value; // push adjusted value into result array
}
var_export($result);
此代码段的优势是零个函数调用和最小的变量声明。
The advantage in this snippet is that there are zero function calls and minimal variables declared.
这篇关于如何减去数组的值但仍在位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!