PHP从数组中删除空值,unset无法正常工作

时间:2017-03-29 00:14:25

标签: php arrays unset

我有一个包含句子的字符串。我希望将这些句子分成一个数组,然后修改每个数组项,包括删除任何空的数组项。

以下是我所拥有的:

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]); 
  }

  //Reinstate the dot
  $item .= '.';
}

然而,这不起作用。我看到额外的'。'如果我在循环中放置print(strlen($item));(在取消设置之后),我会看到一些0结果。

我知道if条件是否得到满足,因为如果我在那里放一个打印件,它会触发0出现的相同次数,例如:

 if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]); 
    }

我在这里做错了吗?

示例$ raw_data字符串。假设我无法控制放在这里的内容。

$raw_data = "Brown fox. Lazy dog."

预期/期望的结果:

$items_array = array("Brown fox.", "Lazy dog.");

目前的结果:

$items_array = array("Brown fox.", "Lazy dog.", ".");

3 个答案:

答案 0 :(得分:1)

实际上很简单,你只缺少一行代码

您的代码

if($item === NULL){
    unset($items_array[$i]); 
}
//Reinstate the dot
$item .= '.';

实现这个目标

if($item === NULL){
    unset($items_array[$i]); 
}
else // <- The else is important
//Reinstate the dot
   $item .= '.';

你需要这一行

$items_array[$i] = $item;

任何可行的工作(包括原始代码)

答案 1 :(得分:0)

目前还不清楚您想要达到的目标,但以下内容可能对您有所帮助。

$raw_data = "Brown fox. Lazy dog.";
$items_array = preg_split('/(?<=[.?!])\s+(?=[a-z0-9])/i', $raw_data);

$sentences = new ArrayIterator($items_array);
for ($sentences->rewind(); $sentences->valid(); $sentences->next()) {
  // Do something with sentence
  print $sentences->current() . "\n";
}

你的工作方法看起来应该像

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array and pass sentence by reference
foreach ($items_array as $i => &$item) {

  //Remove any whitespace at front of item
  $item = ltrim($item);

  //Check if array item is empty and unset (and continue)
  if(empty($item)){
    unset($items_array[$i]);
    continue;
  }
  // Reinstate the dot
  $item .= '.';
}

答案 2 :(得分:0)

我会这样做:

$items_array = array_map(function($v) { return ltrim($v).'.'; },
                         array_filter(explode('.', $raw_data)));
  • .
  • 上爆炸
  • 过滤空白项目
  • 将每个项目映射到修剪并添加.