2014-04-09 2 views
1

설명하는 방법을 모르겠지만 예제를 드리겠습니다. 다만,배열 내용 태그 달기

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 
) 

통과시키는 배열 키는 태그가없는 경우 :

나는이이 배열을 변환 할 수있는 방법

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

입니다 (PHP에서) 배열을 가지고 에서 [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)); 
,536

를 한 일이다

이 반환

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

을 추가했습니다. Dave에게 감사드립니다. – 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 
관련 문제