2014-04-09 47 views
1

我真的不知道如何解釋這一點,但我會舉一個例子。標記數組內容

我有一個數組(在PHP),這是

array(
    [0] => some string is here 
    [1] => some more string here 
    [2] => [TAG] 
    [3] => something is here 
    [4] => this string needs tag too 
) 

我怎麼可以這樣數組轉換成這樣:

array(
[0] => [ALL] 
[1] => some string is here 
[2] => [ALL] 
[3] => some more string here 
[4] => [TAG] 
[5] => something is here 
[6] => [ALL] 
[7] => this string needs tag too 
) 

如果透水數組鍵沒有一個標籤,只是增加了[ALL]標籤

這是我到目前爲止已經完成

$a = "some string is here 
some more string here 
[TAG] 
something is here 
this string needs tag too"; 

$cleanarray = explode("\n", $a); 
for ($x = 0; $x < count($cleanarray); $x++) { 
    $pervline = $x - 1; 
    if ((substr($cleanarray[$pervline], 0,1) != '[') && (substr($cleanarray[$x], 0,1) != '[')) { 
     $cleanarray[$x]="[ALL]\n".$cleanarray[$x]; 
    } 
} 
$cleanarray = explode("\n", implode("\n", $cleanarray)); 

它返回:

Array 
(
    [0] => [ALL] 
    [1] => some string is here 
    [2] => some more string here 
    [3] => [TAG] 
    [4] => something is here 
    [5] => [ALL] 
    [6] => this string needs tag too 
) 
+2

你可以編寫一些代碼來做到這一點。如果你卡住了,再問一次。 –

+0

[TAG]和[ALL]是數組? –

+0

@PragneshChauhan他們是字符串。我剛剛添加了代碼 – user3513546

回答

1

試試這個:

<?php 

$array = array(
    'some string is here', 
    'some more string here', 
    '[TAG]', 
    'something is here', 
    'this string needs tag too' 
); 

print_r($array); 

$tag = '[TAG]'; 
$size = count($array); 

for ($i = 0; $i < $size; $i++) 
    if ($array[$i - 1] !== $tag && $array[$i] !== $tag) { 
     array_splice($array, $i, 0, array('[ALL]')); 
     $i++; 
     $size++; 
    } 

print_r($array); 

Output

Array 
(
    [0] => some string is here 
    [1] => some more string here 
    [2] => [TAG] 
    [3] => something is here 
    [4] => this string needs tag too 
) 
Array 
(
    [0] => [ALL] 
    [1] => some string is here 
    [2] => [ALL] 
    [3] => some more string here 
    [4] => [TAG] 
    [5] => something is here 
    [6] => [ALL] 
    [7] => this string needs tag too 
) 
+0

,效果很好,謝謝戴夫 – user3513546

0

你會實現它通過剪接和切片的組合。

如:

$half1 = array_slice($array, 0, 2); // first 2 
$half2 = array_slice($array, 3, 2); // last 2 
$half = array_splice($array, 2, 0); // [TAG] 

$list = array(); 
foreach ($half1 as $h) { 
    $list[] = '[ALL]'; 
    $list[] = $h; 
} 
$list[] = $half; 
$list[] = $half2[0]; 
$list[] = '[ALL]'; 
$list[] = $half2[1]; 

print_r($list); // should return your array