用一个单词连接每两个数组值,然后用逗号连接这些字符串

问题描述 投票:0回答:6

我的数组是:

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

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

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

我想要 0 带有 1 和 2 带有 3 等等,它们之间带有“ts”。 在两个“ts”之后,应该加一个逗号。像这样:

1ts4,2ts5,3ts6,4ts7

总结:我希望它不要使用奇怪的逗号(与我所说的内爆),而是“ts”(

1ts4,2ts5,3ts6,4ts7

php arrays implode
6个回答
2
投票

尝试下面的代码:-

$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);

已编辑


2
投票

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


2
投票

你可以像下面这样做:-

<?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


1
投票

我知道我可能会迟到回答,但是如果不使用

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

0
投票

还有另一种方法:

<?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);
?>

输出:

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


0
投票

另一种方式:

$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 );
© www.soinside.com 2019 - 2024. All rights reserved.