php에서 어레이 값의 공백을 잘라내는 방법
다음과 같은 배열이 있습니다.
$fruit = array(' apple ','banana ', ' , ', ' cranberry ');
양쪽에 공백이 없는 값을 포함하는 배열을 원합니다만, php에서 이를 수행하는 방법은 빈 값을 포함할 수 있습니다.출력 배열은 다음과 같습니다.
$fruit = array('apple','banana', ',', 'cranberry');
array_map 및 다듬다은 작업을 수행할 수 있습니다.
$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);
다차원 프루프 솔루션:
array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});
array_walk()와 함께 사용할 수 있다trim()가지런히 하다
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
http://www.php.net/manual/en/function.trim.php 에서 두 번째 예를 참조하십시오.
다차원 배열을 사용할 때 기존 답변에 문제가 있었습니다.이 솔루션은 나에게 효과가 있다.
if (is_array($array)) {
foreach ($array as $key => $val) {
$array[$key] = trim($val);
}
}
어레이가 다차원일 경우 다음과 같이 동작합니다.
//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
if($data == null)
return null;
if(is_array($data)){
return array_map('trimData', $data);
}else return trim($data);
}
하나의 샘플 테스트는 다음과 같습니다.
$arr=[" aaa ", " b ", "m ", [" .e ", " 12 3", "9 0 0 0 "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
1차원 어레이 또는 다차원 어레이의 가장 깊은 치수를 트리밍 및 인쇄하려면 다음을 사용하십시오.
foreach($array as $key => $value)
{
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
}
1차원 어레이 또는 다차원 어레이의 가장 깊은 치수를 자르고 싶지만 인쇄하고 싶지 않은 경우 다음을 사용하십시오.
$array = array_map('trim', $array);
$fruit= array_map('trim', $fruit);
array_map('trim', $data)모든 서브어레이를 로 변환하다null문자열에 대해서만 공간을 잘라내고 다른 유형은 그대로 두어야 하는 경우 다음을 사용할 수 있습니다.
$data = array_map(
function ($item) {
return is_string($item) ? trim($item) : $item;
},
$data
);
어소시에이트 어레이의 요소를 잃고 싶지 않은 경우는,array_walk또는array_map!
Foreach 솔루션의 약간 더 짧은 버전:
foreach($array as &$val)
$val = trim($val);
이것은 관련지어 어레이에 유효합니다.
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function generateRandomSpaces() {
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++) {
$output .= " ";
}
return $output;
}
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
}
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
foreach ($array as $index => $elem) {
$array[$index] = trim($elem);
}
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
for ($j = 0; $j < count($array) - 1; $j++) {
$array[$j] = trim($array[$j]);
}
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
상기 코드의 출력은 다음과 같습니다.
어레이 맵: 8.6775720119476초
어레이 워크: 10.423238992691초
포어치: 7.3502039909363초
시간: 9.8266389369965초
물론 이 값은 바뀔 수 있지만, 나는 foreach가 최선의 선택이라고 말하고 싶다.
값이 NULL인 경우 array_map 변경 유형으로 트리밍합니다.
더 나은 방법:
$result = array_map(function($v){
return is_string($v)?trim($v):$v;
}, $array);
regex를 사용하여 모든 공간을 트리밍하거나 어레이 항목을 최소화할 수 있습니다.
$array = array_map(function ($item) {
return preg_replace('/\s+/', '', $item);
}, $array);
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trim_value(&$value)
{
$value = trim($value);
}
// ut_sreco_dis Module
public function disExcelUpload($file=""){
ini_set('MAX_EXECUTION_TIME', -1);
ini_set('memory_limit', '-1');
$file_upload = $file;
if (isset($file_upload) && !empty($file_upload)){
//You can add directly the Composer Autoloder in your controller:
require FCPATH . 'vendor/autoload.php';
try{
$objPHPExcel = PHPExcel_IOFactory::load($file_upload);
}
catch (Exception $e){
die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$highestco = $sheet->getHighestDataColumn();
$arrayCount = count($allDataInSheet);
$now = date("Y-m-d H:i:s");
$flag = 0;
$check_template = array(
'A' => 'FIN_ID',
'B' => 'SECCODE',
'C' => 'SCHEME_NO',
'D' => 'SEC_SCH',
'E' => 'DISNO',
'F' => 'DISQTY',
'G' => 'BILLQTY',
'H' => 'BILLREF',
'I' => 'BILLDT',
);
$input_template = $allDataInSheet[1];
array_walk($input_template, $this->trim_value);
$result = array_diff($check_template, $input_template);
if(empty($result))
{
$this->srObject->truncTableDis();
# loop for inserting data
for ($i = 2,$j=0; $i <= $highestRow; $i++){
$db_ch_ot = 64;
$fin_id = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_code = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sch_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$sec_sch = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_no = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$dis_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_qty = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_ref = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
$bill_dt = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
if(empty($bill_dt)){
$bill_dt = null;
}else{
$dip_dt = date("Y-m-d",strtotime($bill_dt));
}
$dt = date('Y-m-d H:i:s');
$insert_data = array(
"fin_id_data" => $fin_id,
"sec_code_data" => $sec_code,
"sch_no_data" => $sch_no,
"sec_sch_data" => $sec_sch,
"dis_no_data" => $dis_no,
"dis_qty_data" => $dis_qty,
"bill_qty_data" => $bill_qty,
"bill_ref_data" => $bill_ref,
"bill_dt_data" => $bill_dt,
"created_at_data" => $dt,
"updated_at_data" => $dt,
);
if($this->srObject->insertSdisData($insert_data))
{
++$flag;
}
} //loop close
} else {
$this->session->set_flashdata('error', 'Error. Invalid Excel Template');
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
$this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
redirect(site_url('schill-bill-checking-suuti/sreco'));
}
}
function trimArray(&$value)
{
$value = trim($value);
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');
array_walk 함수를 사용하면 어레이 요소에서 공간을 제거할 수 있으며 요소는 동일한 배열로 결과를 반환합니다.
언급URL : https://stackoverflow.com/questions/5762439/how-to-trim-white-spaces-of-array-values-in-php
'programing' 카테고리의 다른 글
| MySQL의 열에 대한 단순 중위수 계산 (0) | 2023.01.24 |
|---|---|
| Vue 3: 메서드 함수에서 상태에 액세스하는 방법 (0) | 2023.01.24 |
| Java 시간대를 GMT/UTC로 강제 적용 (0) | 2023.01.24 |
| NumPy 어레이에 열을 추가하려면 어떻게 해야 합니까? (0) | 2023.01.24 |
| 다음 클래스를 인스턴스화할 수 없습니다. - Android.support.v7.199.툴바 (0) | 2023.01.24 |