1

我有 30 行文本并分解成由“\n”分隔的数组。结果如下:

[1]=> string(121) "In recent years, the rapid growth" 
[2]=> string(139) "information technology has strongly enhanced computer systems" 
[3]=> string(89) "both in terms of computational and networking capabilities" 
[4]=> string(103) "-------------------------" 
[5]=> string(103) "these novel distributed computing scenarios"
 .
 .
[30]=> string(103) "these computer safety applications. end"

在这种情况下,我需要删除“-------------”下面的所有数组并产生如下输出:

[1]=> string(121) "In recent years, the rapid growth" 
[2]=> string(139) "information technology has strongly enhanced computer systems" 
[3]=> string(89) "both in terms of computational and networking capabilities" 

知道怎么做吗?谢谢。

迈克尔解决问题的方法

$i = 0;
$new_arr = array();
while ($array[$i] != "-------------------------") {
  // Append lines onto the new array until the delimiter is found
  $new_arr[] = $array[$i];
  $i++;
}
print_r($new_arr);
4

5 回答 5

1

例如

function getMyArray( $array ){

     $myArray = array();
     foreach( $array as $item ){
         if ( $item == '-------------------------' ){ return $myArray; }
         $myArray[] = $line;
     }
     return $myArray'
}
于 2012-04-17T13:19:26.717 回答
1

最佳解决方案:

使用array_search()然后截断数组array_splice()

$key = array_search("-------------------------", $array);
array_splice($array, $key);

明显的解决方案:

您可以循环将输出复制到新数组。想到的第一个例子:

$i = 0;
$new_arr = array();
while ($array[$i] != "-------------------------") {
  // Append lines onto the new array until the delimiter is found
  $new_arr[] = $array[$i];
  $i++;
}
print_r($new_arr);
于 2012-04-17T13:19:35.620 回答
1

数组搜索

取消设置

你也可以使用 array_slice

于 2012-04-17T13:20:55.953 回答
0
foreach($array as $key => $value)
{
    if($value == '-------------')
          break;
    else
          $new_array[$key]=$value;
}
于 2012-04-17T13:20:46.587 回答
0

您可以使用它array_search来查找其所在位置的密钥。

来自 PHP.net:

<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
?>

获得密钥后,您可以执行以下操作:

<?php
while($key < count($array) )
{
   $array = unset($array[$key]);
   $key++;
}
?>
于 2012-04-17T13:22:14.633 回答