我有一个这样的数组:
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
当值last
(此处sendby
和3
)是整个数组的最后一个时,我希望值8
为1!我怎么能这样做?
答案 0 :(得分:2)
获取最后2个值并与数组[3,8]进行比较
// get array of sendby values
$temp = array_column($array, 'sendby');
// get array with two last values
$temp = array_slice($temp, -2);
// Check
if ($temp == [3,8]) {
$value = 1;
}
else {
$value = 0;
}
或一行
$value = array_slice(array_column($array, 'sendby'), -2) == [3,8] ? 1 : 0;
根据评论进行更新
// get array with two last values
$temp = array_slice(array_column($array, 'sendby'), -2);
foreach($array as &$x) {
// If current send by is in $temp array
if(in_array($x['sendby'], $temp)) {
$x['last'] = 1;
}
else {
$x['last'] = 0;
}
}
print_r($array);
答案 1 :(得分:1)
您可以使用数组来协助该ID的现有发生。我有一个工作示例(在php沙箱上测试):
$array = array(
0 => array
(
'sendby' => 3,
'refresh' => 0,
),
1 => array
(
'sendby' => 3,
'refresh' => 1,
),
2 => array
(
'sendby' => 8,
'refresh' => 1,
)
);
$ocurrences = [];
foreach($array as $key => $elem ){
$id = $elem['sendby'];
if (isset($ocurrences[$id])) {
$array[$ocurrences[$id]]['last'] = 0;
$array[$key]['last'] = 1;
$ocurrences[$id] = $key;
} else {
$ocurrences[$id] = $key;
$array[$key]['last'] = 1;
}
}
echo print_r($array, 1);
结果:
Array
(
[0] => Array
(
[sendby] => 3
[refresh] => 0
[last] => 0
)
[1] => Array
(
[sendby] => 3
[refresh] => 1
[last] => 1
)
[2] => Array
(
[sendby] => 8
[refresh] => 1
[last] => 1
)
)
基本上我使用了一个数组,其中包含' sendby'数组的索引。 $occurences
数组的元素带有最后一个被检查元素的键。
答案 2 :(得分:0)
假设你的数组是$ array; 您可以遍历它,如果它是最后一个元素,则将[last]设置为1,否则设置为0;
在填充数组后尝试运行以下代码。
$i =1;
foreach($array as $ar) {
$ar->last = ($i == count($array) && ($ar->sendby == 3 || $ar->sendby == 8)) ? 1 : 0;
$i++;
}
答案 3 :(得分:0)
$ count = count($ arr);
$ i = 0;
foreach($ arr as $ key => $ val){
if(++ $ I === $ count){
Sub SumCols()
Dim ws As Worksheet
Set ws = Sheets("Recon")
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
Range("E" & i).Value = Range("C" & i).Value + Range("D" & i).Value
Next i
End Sub
}
}