替换数组中的一个字符串,但在php中保持其他字符串不变

Say I have an array of strings like this:

$in_arr = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];

I would like an efficient way to merge all a's into a single value but leave the b's untouched so the result will be:

['a', 'b', 'b', 'a', 'b', 'b', 'a', 'b']

With array_reduce:

$res = array_reduce($arr, function ($c, $i) {
    if ( $i!='a' || end($c)!='a' )
        $c[] = $i;
    return $c;
}, []);

This is a possible solution:

<?php
define('ASPECT', 'a');
$input = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];
$output = [];
array_walk($input, function($entry) use (&$output) {
    if (($entry != ASPECT) || (end($output) != ASPECT)) {
        $output[] = $entry;
    }
});
print_r($output);

The output obviously is:

Array
(
    [0] => a
    [1] => b
    [2] => b
    [3] => a
    [4] => b
    [5] => b
    [6] => a
    [7] => b
)

Using a simple loop...

$in_arr = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];
for ( $i = 0; $i <count($in_arr)-1; $i++ )    {
    if ( $in_arr[$i] == 'a' && $in_arr[$i+1] == 'a')    {
        unset($in_arr[$i]);
    }
}

print_r($in_arr);

You could iterate through the list and only add strings to a new list if they're not your key string or if they are different from the previous string, something like this:

$in_arr = ['a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b'];
$new_arr = [];

$last = '';
$key = 'a';

foreach ($in_arr as $item) { 
    if ($key == $item and $item == $last) {
        continue;
    }

    $last = $item;
    array_push($new_arr, $item);
}

echo "[";
foreach( $new_arr as $value ){
    echo $value.", ";
}
echo "]";

produces

[a, b, b, a, b, b, a, b, ]

Edit: PHP sandbox

You Require code :

<?php
$in_arr = array('a', 'a', 'b', 'b', 'a', 'b', 'b', 'a', 'a', 'b');

$last_temp = '';
for($i=0;$i<count($in_arr);$i++)
{
    if($last_temp == $in_arr[$i] && $in_arr[$i]=='a')
    {
        unset($in_arr[$i]);
        $in_arr = array_values($in_arr);
    }
    else
    {
        $last_temp = $in_arr[$i];
    }
}

echo json_encode($in_arr);

Output :

["a","b","b","a","b","b","a","b"]