简体   繁体   English

从特定的偏移量开始删除所有数组值

[英]Deleting all array values from a specific offset and on

I have an array that has 120~ or so offsets and I was wondering how you would delete all the values of said array after a certain offset containing a specified string. 我有一个具有120〜左右偏移量的数组,我想知道如何在包含指定字符串的特定偏移量后删除所述数组的所有值。 For example: Offset [68] has the string 'Overflow'. 例如:偏移[68]具有字符串'Overflow'。 I want to remove everything including 68 and beyond and rebuild the array (with its current sorting in tact). 我想删除所有内容,包括68及以后的内容,并重建数组(其当前排序完好无损)。

I tried messing around with slice and splice but I can't seem to get it to return the right values. 我试图弄乱slice和splice,但是我似乎无法让它返回正确的值。 I was also thinking of just grabbing the offset number that contains 'Overflow' and then looping it through a for statement until $i = count($array); 我还考虑过只获取包含'Overflow'的偏移量,然后通过for语句循环它,直到$i = count($array); but that seems a little more intensive than it should be. 但这似乎比应有的强度要大。

Would this be the best way? 这是最好的方法吗? Or is there some function to do this that I'm just using wrong? 还是有一些功能我只是用错了?

使用array_slice()

$desired = array_slice($input, 0, $upTo);

First you need to find the string occurrence in the array, and, if the value was found, trim the array from that point; 首先,您需要找到数组中出现的字符串,如果找到了值,则从该点修剪数组;

function removeString($string, $array)
{
  # search for '$string' in the array
  $found = array_search($string, $array);

  if ($found === false) return $array; # found nothing

  # return sliced array
  return array_slice($array, $found);
}

And if you need to make the array sequential (to avoid surprises due to missing offsets), you can always add in the first line $array = array_values($array) . 而且,如果需要使数组顺序排列(以避免由于缺少偏移而产生意外情况),则始终可以在第一行中添加$array = array_values($array) This will reorganize the array values in a new array with ordered offsets: 0, 1, 2, 3, 4... 这将以偏移量为0、1、2、3、4 ...的新数组重新组织数组值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM