PHP - 如果找到密钥,则删除后续数组值

时间:2015-09-30 07:27:49

标签: php arrays

$ week_link_arr

Array
(
    [0] => 1-4_1*Oct-2015
    [1] => 5-11_2*Oct-2015
    [2] => 12-18_3*Oct-2015
    [3] => 19-25_4*Oct-2015
    [4] => 26-31_5*Oct-2015
)

$ current_week_url

1-4_1*Oct-2015

尝试使用array_search获取密钥,并在未设置的情况下将其删除(如果找到):

if (($key = array_search($current_week_url, $week_link_arr)) !== false) {
    unset($week_link_arr[$key]);
    }

输出

Array
(
    [1] => 5-11_2*Oct-2015
    [2] => 12-18_3*Oct-2015
    [3] => 19-25_4*Oct-2015
    [4] => 26-31_5*Oct-2015
)

这将删除找到的密钥。相反,如果找到key,我需要删除后续的数组元素。使用键1-4_1*Oct-2015

执行输出
Array
(
    [0] => 1-4_1*Oct-2015
)

如果密钥为5-11_2*Oct-2015,则

Array
(
    [0] => 1-4_1*Oct-2015
    [1] => 5-11_2*Oct-2015
)

2 个答案:

答案 0 :(得分:2)

你是说这个吗?

if (($key = array_search($current_week_url, $week_link_arr)) !== false) {
      $week_link_arr = array_slice($week_link_arr, 0, $key + 1);
}

答案 1 :(得分:1)

在这种情况下,您的密钥是数组中的索引 因此,您只需删除此键与数组其余部分之间的键

即可
if (($key = array_search($current_week_url, $week_link_arr)) !== false) {
    array_splice($week_link_arr, $key, count($week_link_arr)-1);
}