-4

我有一个数组:

$array = array("1" => "", "2" => "" , "3" => "data1", "4" => "" , "5" => "data2", "6" => "" );

声明时for保留了一些空值。数组可能太长。我想要一种在 PHP 中查找填充数组编号的方法。

4

4 回答 4

4

检查这个,会给你所有空数组键

  <?php
      $array = array("1" => "", "2" => "" , "3" => "data1", "4" => "" , "5" => "data2", "6" => "" );
      $new = array_filter($array, 'strlen');
      $result = array_diff($array, $new);
       print_r($result);
    ?>

如果要删除空值键, 请使用 array_filter

    <?php
      $array = array("1" => "", "2" => "" , "3" => "data1", "4" => "" , "5" => "data2", "6" => "" );
      $new = array_filter($array, 'strlen');
      print_r($new);
    ?>
于 2012-08-30T11:33:21.427 回答
1

像这样的东西?

$newArray = array();

foreach($array as $key=> $value)
{
   if($value != '')
       $newArray[$key] = $value;
}

print_r($newArray);
于 2012-08-30T11:32:35.170 回答
1
$array = array("1" => "", "2" => "" , "3" => "data1", "4" => "" , "5" => "data2", "6" => "" );

$array_with_keys = array();


foreach($array as $key=> $value)
{
   if($value != '')
       $array_with_keys[] = $key;
}

print_r($array_with_keys);

由于您只需要键,这将返回一个带有键的数组,您可以使用它来使用foreach循环更新数据库

于 2012-08-30T11:45:02.533 回答
0

我不是 100% 确定你想要什么,但我认为这可能会对你有所帮助。如果这不是你想要的,请告诉我。

foreach ($array as $v) {
  if ($v) {
    // this value is not empty
  }
}
于 2012-08-30T11:32:39.707 回答