欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

数组重新组合

程序员文章站 2022-05-09 11:55:32
...
1,如何将数组arr1转化成arr2?

arr1 = [

['tracking1','abc@qq.com','80'],
['tracking1','abc@qq.com','50'],
['tracking2','efg@qq.com','60'],
['tracking2','efg@qq.com','30'],

];

arr2 = [

['tracking1','abc@qq.com',['80','50']],
['tracking2','efg@qq.com',['60','30']],

];

回复内容:

1,如何将数组arr1转化成arr2?

arr1 = [

['tracking1','abc@qq.com','80'],
['tracking1','abc@qq.com','50'],
['tracking2','efg@qq.com','60'],
['tracking2','efg@qq.com','30'],

];

arr2 = [

['tracking1','abc@qq.com',['80','50']],
['tracking2','efg@qq.com',['60','30']],

];

思路很简单,就是把数组的第一和第一列的值作为一个唯一key写入,感觉楼上代码有点多,简洁代码如下

$arr1 = [
    ['tracking1','abc@qq.com','80'],
    ['tracking1','abc@qq.com','50'],
    ['tracking2','efg@qq.com','60'],
    ['tracking2','efg@qq.com','30'],
];

$arr2 = [];
foreach ($arr1 as $data) {
    list($account,$mail,$val) = $data;
    isset($arr2[$account.$mail]) || $arr2[$account.$mail]=[$account,$mail,[]];
    array_push($arr2[$account.$mail][2],$val);
}
$arr2 = array_values($arr2);
var_dump($arr2);

我给个思路,先遍历判断arr1[0]是否一样,一样就往一个新数组中插入,在这基础判断[1]是否相同,相同就插入值,不同则合并成一个数组,以此类推

$arr = [['tracking1','abc@qq.com','80'],
['tracking1','abc@qq.com','50'],
['tracking2','efg@qq.com','60'],
['tracking2','efg@qq.com','30']];

$finalArr = [[[]]];
$mailArr =[];
foreach ($arr as $k=>$v){
    $mailKey = array_search($v[1],$mailArr);
    if($mailKey!==false){
        array_push($finalArr[$mailKey][2],$v[2]);
    }else{
        $finalArr[$k] = $v;
        $finalArr[$k][2] = [$v[2]];
        $mailArr[$k]=$v[1];
    }
}
$finalArr = array_values($finalArr);
var_dump($finalArr);

14行功能代码,不要太简单。

说下我的思路,题主这个数组,拆分开其实就是两个部分,每个数组里的v0、v1值,和v2值。

$new = array(); 
$flag = 1;
foreach ($arr as $key => $value) {
  $newss[$value[0].'-'.$value[1]][] = $value[2];  //取出重复小标0 1的值 
  $news = array($value[0], $value[1]);
  foreach ($new as $k => $v) {
    if(!array_diff($v,$news )) { //如果
      $flag = 2;
      break;
    }
  }
  if($flag == 1) {
    $new[] = array($value[0], $value[1]);
  }
  $flag = 1;
}
foreach ($new as $key => $value) {
  $new[$key][2] = $newss[$value[0].'-'.$value[1]];
}
var_dump($new);exit;

    $arr1 = [    
        ['tracking1','abc@qq.com','80'],
        ['tracking1','abc@qq.com','50'],
        ['tracking2','efg@qq.com','60'],
        ['tracking2','efg@qq.com','30'],
    ];
    
    $arr2 = [
        ['tracking1','abc@qq.com',['80','50']],
        ['tracking2','efg@qq.com',['60','30']],
    ];

    define("CUSTOM_SEPA", "_");

    function t($a0){
        $r = [];
        $res = [];
        foreach($a0 as $v){
            $r[$v[0].CUSTOM_SEPA.$v[1]][] = $v[2];
        }
        foreach($r as $k=>$v){
            $s = explode(CUSTOM_SEPA, $k);
            $s[] = $v;
            $res[] = $s;
        }
        return $res;
    }

    $res = t($arr1);
    print_r($res == $arr2);
相关标签: php 数组