只是一种添加剂。
我知道这是旧,但我想添加一个我自己没有想到的解决方案。在寻找不同的解决方案时发现了这个问题,只是想,“好吧,当我在这里的时候。”
首先,Neal 的答案很好,在您运行循环后非常适合使用,但是,我更喜欢一次完成所有工作。当然,在我的具体情况下,我必须比这里的这个简单示例做 更多 工作,但该方法仍然适用。我看到其他几个人建议 foreach 循环,但是,由于野兽的性质,这仍然让您下班。通常我建议像foreach 这样更简单的东西,但是,在这种情况下,最好记住老式的for loop 逻辑。只需使用 i!要保持适当的索引,只需在每次删除 Array 项后从 i 中减去。
这是我的简单工作示例:
$array = array(1,2,3,4,5);
for ($i = 0; $i < count($array); $i++) {
if($array[$i] == 1 || $array[$i] == 2) {
array_splice($array, $i, 1);
$i--;
}
}
将输出:
array(3) {
[0]=> int(3)
[1]=> int(4)
[2]=> int(5)
}
这可以有很多简单的实现。例如,我的确切情况需要根据多维值在数组中保存最新项目。我会告诉你我的意思:
$files = array(
array(
'name' => 'example.zip',
'size' => '100000000',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '10726556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '110726556',
'type' => 'application/x-zip-compressed',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example2.zip',
'size' => '12356556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
'deleteUrl' => 'server/php/?file=example2.zip',
'deleteType' => 'DELETE'
)
);
for ($i = 0; $i < count($files); $i++) {
if ($i > 0) {
if (is_array($files[$i-1])) {
if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
$i--;
array_splice($files, $i, 1);
}
}
}
}
将输出:
array(1) {
[0]=> array(6) {
["name"]=> string(11) "example.zip"
["size"]=> string(9) "110726556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
}
[1]=> array(6) {
["name"]=> string(11) "example2.zip"
["size"]=> string(9) "12356556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
}
}
如您所见,我在拼接之前操纵了 $i,因为我试图删除前一个项目,而不是当前项目。