在独特的案例

时间:2016-09-23 04:27:02

标签: php arrays

我有以下2个数组变量。

$a = array("triple","triple","double","single","single");
$b = array("444","555","33","2","3");

我需要将这两个数组转换为此数组模式

$array = array(
    "triple"=>array("444","555"),
    "double"=>array("33"),
    "single"=>array("2","3")
);

这样我就能得到像这样的结果

triple(444 | 555) double(33) single(2 | 3)

谁能帮帮我?感谢

2 个答案:

答案 0 :(得分:1)

只需使用array_combine$b作为键,使用$a作为值,然后转移到使用键对其进行分组的新容器:

$array = array();
foreach(array_combine($b, $a) as $k => $v) {
    $array[$v][] = $k;
}

出于演示目的,只需implode他们:

foreach($array as $key => $numbers) {
    $href = implode('|', $numbers);
    $numbers = $key . '(' . implode(' | ', $numbers) . ')' . ' ';
    echo "<a href='aaa.php?numbers=$href'>$numbers</a>";
}

答案 1 :(得分:0)

您可以使用PHP的Array_unique ... Follow this link

并执行以下操作..

$arr = [];
foreach($a as $value) {

 if ( $value == 'tripple' ) {
   foreach( $b as $val ) if( strlen($val) == 3 ) $arr[$value][] = $val;
 }

if ( $value == 'double' ) {
   foreach( $b as $val ) if( strlen($val) == 2 ) $arr[$value][] = $val;
 }

if ( $value == 'single' ) {
   foreach( $b as $val ) if( strlen($val) == 1 ) $arr[$value][] = $val;
 }

}

这应该有用......