string(44) "苹果,香蕉,苹果"} [3] => array(6) {["job_name"] => stri">
当前位置:Gxlcms > PHP教程 > PHP数组操作去重T.T

PHP数组操作去重T.T

时间:2021-07-01 10:21:17 帮助过:8人阅读

大神们 我的数组长这个样子
array(2) {
[14] => array(6) {

["job_name"] => string(44) "苹果,香蕉,苹果"

}
[3] => array(6) {

["job_name"] => string(44) "梨子,梨子,西红柿"

}
}

我想让它变成

array(2) {
[14] => array(6) {

["job_name"] => string(44) "苹果2,香蕉1"

}
[3] => array(6) {

["job_name"] => string(44) "梨子2,西红柿1"

}
}

这个酱紫 会不会很难T.T 有朋友会么Q.Q

回复内容:

大神们 我的数组长这个样子
array(2) {
[14] => array(6) {

["job_name"] => string(44) "苹果,香蕉,苹果"

}
[3] => array(6) {

["job_name"] => string(44) "梨子,梨子,西红柿"

}
}

我想让它变成

array(2) {
[14] => array(6) {

["job_name"] => string(44) "苹果2,香蕉1"

}
[3] => array(6) {

["job_name"] => string(44) "梨子2,西红柿1"

}
}

这个酱紫 会不会很难T.T 有朋友会么Q.Q

array_walk($arr, function(&$item) {
    $item['job_name'] = join(',', array_unique(explode(',', $item['job_name'])));
});

没看清楚题目, 下面是修改后的答案

array_walk($arr, function(&$item) {
    $after = array_values(array_unique(explode(',', $item['job_name'])));
    foreach ($after as $key=>$value) {
        preg_match_all("/$value/", $item['job_name'], $matches);
        $after[$key] = $value . count($matches[0]);
    }
    $item['job_name'] = join(',', $after);
});

意思就是这个二维数组中的job_name字段,如果有重复的,就在重复的后面设置对应的重复数即可,对不!

foreach ($arr as $fruits){
    $fruits_array = explode(',',$fruits['job_name']);
    $count_array = array();
    foreach ($fruits_array as $fruit){
        $count_array[$fruit][] =1;
    }
    $sum_data =array();
    foreach ($count_array as $fruit=>$fruit_array){
        $sum_data[] = $fruit.  count($fruit_array);
    }
    $sum_data = implode(',',$sum_data);
    $return_data[]["job_name"] = $sum_data;

}

function dealArr($arr=array()){
    foreach ($arr as $key => $value) {
        $a0[$key] = explode(',',$value['job_name']);//分割字符串
        $a1[$key] = array_count_values($a0[$key]);//统计个数
        $temp=array();
        foreach ($a1[$key] as $key2 => $value2) {
            $temp[$key2]=$key2.$value2;
        }
        $res[$key]['job_name']=implode(',',$temp);//字符串转数组
        
    } 
    return $res;
}

输入数组相关的错误检查暂未处理

$arr[14]['job_name']="苹果,香蕉,苹果";
$arr[3]['job_name']="梨子,梨子,西红柿";
var_dump(dealArr($arr));

foreach ($arr as &$val){
    $job_name_array = explode(',',$val['job_name']);
    $return = array_count_values($job_name_array);
    $str = '';
    foreach ($return as $key => $value){
        $str .= $key.$value.',';
    }
    $str = rtrim($str,",");
    $val['job_name'] = $str;
 }

人气教程排行