我真的不知道如何解释这个,但我会举一个例子。
我有一个数组(在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
)
答案 0 :(得分: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);
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
)
答案 1 :(得分: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