在 php 中将数组的每个值组合到单个数组中



我想将两个数组中的每个值组合成单个数组,并有这样的代码,

$k = 'a,b';
$db = '01,02,03,04,05';
$dbe = explode(",", $db);
$lenght = count($dbe);
$kdata = explode(",", $k);
$dbdata = explode(",", $db);
if(sizeof($kdata) > sizeof($dbdata)){
$length = count($kdata);
}else{
$length = count($dbdata);
}       
for($i=0; $i<$length; $i++)
{
foreach( $kdata as $p => $kop)
{
echo $kop.$dbdata[$p]. ",";
}
}

并得到结果;

a01,b02,a01,b02,a01,b02,a01,b02,a01,b02,

但是结果不是我预期的,我想要的结果是这样的:

a01, a02, a03, a04, a05, b01, b02, b03, b04, b05,

如何解析此代码以获得我想要的结果。

我们做一个数组,然后我们想要一些东西并去做。

<?php
$k = 'a,b';
$db = '01,02,03,04,05';

$kdata = explode(",", $k);
$dbdata = explode(",", $db);

foreach($kdata as $val){
foreach($dbdata as $value){
$items[] = $val.$value;
}
}
$result = implode(", ", $items);
echo $result;
?>

explode()构建数组之后,您可以执行嵌套foreach()以输出结果...

$k = 'a,b';
$db = '01,02,03,04,05';
$kdata = explode(",", $k);
$dbdata = explode(",", $db);
foreach ( $kdata as $prefix) {
foreach( $dbdata as $kop)
{
echo $prefix.$kop. ", ";
}
}

相关内容

  • 没有找到相关文章

最新更新