两两内爆数组字符串 - php

implode array strings two by two - php

我的数组是:

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

我使用这段代码: 内爆(“,”,$输出);

但它 returns 这个: 1,4,2,5,3,6,4,7,6

我想要 0 附带 1,2 附带 3 等等,它们之间有 "ts"。 在它们都带有 "ts" 之后,它应该带有一个逗号。像这样 : 1ts4,2ts5,3ts6,4ts7

总结:我希望它把 "ts" (1ts4,2ts5,3ts6,4ts7)

代替奇数逗号(用我说的内爆)

您可以使用array_chunk函数先将数组拆分成多个部分,然后根据需要将它们内爆。

你可以像下面那样做:-

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

$arr = Array
(
    0 => 1,
    1 => 4,
    2 => 2,
    3 => 5,
    4 => 3,
    5 => 6,
    6 => 4,
    7 => 7
);

$new_array = array_chunk($arr,2); // break the array into sub-arrays of two-two values each

$my_string = ''; // an empty string
foreach ($new_array as $new_arra){ // iterate though the new chunked array

    $my_string .= implode('ts',$new_arra).','; // implode the sub-array and add to the variable
}

echo trim($my_string,','); // echo variable

输出:- 1ts4,2ts5,3ts6,4ts7

https://eval.in/686524

试试下面的代码:-

$arr = [1,4,2,5,3,6,4,7];
$strArr= [];
for($i=0;$i<count($arr);$i=$i+2){
  $strArr[] = "{$arr[$i]}ts{$arr[$i+1]}";
} 
echo implode(',',$strArr);

已编辑

这是另一种方式:

<?php 
$a = Array(0 => 1,1 => 4,2 => 2,3 => 5,4 => 3,5 => 6,6 => 4,7 => 7);// your array
$i=1;
foreach ($a as $key => $value) {
    if ($i % 2 != 0) { 
        $newArr[] = $value."ts".$a[$i];
    }
    $i++;
}
print_r($newArr);
?>

输出:

Array ( [0] => 1ts4 [1] => 2ts5 [2] => 3ts6 [3] => 4ts7 )

我知道我可能会迟到,但如果不使用 array_chunk 函数并使用像 as

这样的单个 for 循环,这可能会有所帮助
$arr = Array
(
    0 => 1,
    1 => 4,
    2 => 2,
    3 => 5,
    4 => 3,
    5 => 6,
    6 => 4,
    7 => 7
);

$res = [];
$count = count($arr);
for($k = 0; $k < $count; $k+=2)
{
    $res[] = isset($arr[$k+1]) ? "{$arr[$k]}ts{$arr[$k+1]}" : $arr[$k];
}

echo implode(",",$res);

输出:

1ts4,2ts5,3ts6,4ts7

另一种方式:

$array = [
    0 => 1,
    1 => 4,
    2 => 2,
    3 => 5,
    4 => 3,
    5 => 6,
    6 => 4,
    7 => 7,
];

$array = array_map( function( $item ) { return implode( 'ts', $item ); }, array_chunk( $array, 2 ) );
echo implode( ',', $array );