我有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);
答案 0 :(得分:1)
例如
function getMyArray( $array ){
$myArray = array();
foreach( $array as $item ){
if ( $item == '-------------------------' ){ return $myArray; }
$myArray[] = $line;
}
return $myArray'
}
答案 1 :(得分: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);
答案 2 :(得分:1)
答案 3 :(得分:0)
foreach($array as $key => $value)
{
if($value == '-------------')
break;
else
$new_array[$key]=$value;
}
答案 4 :(得分: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++;
}
?>