大神們 我的陣列長這個樣子
array(2) {
[14] => array(6) {
<code>["job_name"] => string(44) "苹果,香蕉,苹果"</code>
}
[3] => array(6) {
<code>["job_name"] => string(44) "梨子,梨子,西红柿"</code>
}
}
我想讓它變成
array(2) {
[14] => array(6) {
<code>["job_name"] => string(44) "苹果2,香蕉1"</code>
}
[3] => array(6) {
<code>["job_name"] => string(44) "梨子2,西红柿1"</code>
}
}
這個醬紫 會不會很難T.T 有朋友會麼Q.Q
大神們 我的陣列長這個樣子
array(2) {
[14] => array(6) {
<code>["job_name"] => string(44) "苹果,香蕉,苹果"</code>
}
[3] => array(6) {
<code>["job_name"] => string(44) "梨子,梨子,西红柿"</code>
}
}
我想讓它變成
array(2) {
[14] => array(6) {
<code>["job_name"] => string(44) "苹果2,香蕉1"</code>
}
[3] => array(6) {
<code>["job_name"] => string(44) "梨子2,西红柿1"</code>
}
}
這個醬紫 會不會很難T.T 有朋友會麼Q.Q
<code class="php">array_walk($arr, function(&$item) { $item['job_name'] = join(',', array_unique(explode(',', $item['job_name']))); });</code>
沒看清楚題目, 以下是修改後的答案
<code class="php">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); });</code>
意思就是這個二維數組中的job_name
字段,如果有重複的,就在重複的後面設置對應的重複數即可,對不!
<code class="php">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; }</code>
<code>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; }</code>
輸入數組相關的錯誤檢查暫未處理
<code>$arr[14]['job_name']="苹果,香蕉,苹果"; $arr[3]['job_name']="梨子,梨子,西红柿"; var_dump(dealArr($arr)); </code>
<code>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; }</code>