빈 배열 요소 제거
내 배열의 일부 요소는 사용자가 제출 한 내용에 따라 빈 문자열입니다. 이러한 요소를 제거해야합니다. 나는 이것을 가지고있다:
foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
하지만 작동하지 않습니다. $linksArray
여전히 빈 요소가 있습니다. 나는 또한 empty()
기능으로 그것을 시도 했지만 결과는 동일합니다.
문자열 배열을 처리 할 때를 사용 array_filter()
하면됩니다.이 모든 것을 편리하게 처리 할 수 있습니다.
print_r(array_filter($linksArray));
있다는 사실에 유의 콜백이 제공되지 않으면 , 어레이의 모든 항목이 동일 FALSE
(참조 논리 값으로 변환 을 제거한다). 따라서 정확한 문자열 '0'
인 요소를 보존 해야하는 경우 사용자 정의 콜백이 필요합니다.
// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));
array_filter
빈 요소를 제거 하는 데 사용할 수 있습니다 .
$emptyRemoved = array_filter($linksArray);
당신이있는 경우 (int) 0
배열에 다음을 사용할 수 있습니다 :
$emptyRemoved = remove_empty($linksArray);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
편집 : 아마도 요소가 그 자체로 비어 있지 않지만 하나 이상의 공백을 포함 할 수 있습니다 ... 사용하기 전에 다음을 사용할 수 있습니다.array_filter
$trimmedArray = array_map('trim', $linksArray);
이 주제에 대한 가장 인기있는 답변은 절대적으로 올바르지 않습니다.
다음 PHP 스크립트를 고려하십시오.
<?php
$arr = array('1', '', '2', '3', '0');
// Incorrect:
print_r(array_filter($arr));
// Correct:
print_r(array_filter($arr, 'strlen'));
왜 이런거야? 단일 '0'문자를 포함하는 문자열도 부울 false로 평가되기 때문에 빈 문자열이 아니더라도 여전히 필터링됩니다. 그것은 버그 일 것입니다.
내장 strlen 함수를 필터링 함수로 전달하면 비어 있지 않은 문자열에 대해 0이 아닌 정수를 반환하고 빈 문자열에 대해 0 정수를 반환하기 때문에 작동합니다. 0이 아닌 정수는 부울로 변환 될 때 항상 true로 평가되고, 0이 아닌 정수는 부울로 변환 될 때 항상 false로 평가됩니다.
따라서 절대적이고 확실한 정답은 다음과 같습니다.
$arr = array_filter($arr, 'strlen');
$linksArray = array_filter($linksArray);
"콜백이 제공되지 않으면 FALSE와 동일한 입력 항목이 모두 제거됩니다." -http : //php.net/manual/en/function.array-filter.php
$myarray = array_filter($myarray, 'strlen'); //removes null values but leaves "0"
$myarray = array_filter($myarray); //removes all null values
당신은 할 수 있습니다
array_filter($array)
array_filter : "콜백이 제공되지 않으면 FALSE와 동일한 입력 항목이 모두 제거됩니다." 이는 값이 NULL, 0, '0', '', FALSE, array () 인 요소도 제거됨을 의미합니다.
다른 옵션은
array_diff($array, array(''))
값이 NULL, ''및 FALSE 인 요소를 제거합니다.
도움이 되었기를 바랍니다 :)
최신 정보
여기에 예가 있습니다.
$a = array(0, '0', NULL, FALSE, '', array());
var_dump(array_filter($a));
// array()
var_dump(array_diff($a, array(0))) // 0 / '0'
// array(NULL, FALSE, '', array());
var_dump(array_diff($a, array(NULL))) // NULL / FALSE / ''
// array(0, '0', array())
요약하자면 :
- 0 또는 '0'은 0과 '0'을 제거합니다.
- NULL, FALSE 또는 ''는 NULL, FALSE 및 ''를 제거합니다.
foreach($linksArray as $key => $link)
{
if($link === '')
{
unset($linksArray[$key]);
}
}
print_r($linksArray);
배열에서 빈 ( ""빈 문자열) 요소를 제거하는 또 다른 라이너입니다.
$array = array_filter($array, function($a) {return $a !== "";});
참고 :이 코드는 의도적으로 null
, 0
및 false
요소를 유지 합니다.
또는 먼저 배열 요소를 트리밍하고 싶을 수도 있습니다.
$array = array_filter($array, function($a) {
return trim($a) !== "";
});
참고 :이 코드는 null
및 false
요소 도 제거합니다 .
요컨대 :
이것은 내 제안 코드입니다.
$myarray = array_values(array_filter(array_map('trim', $myarray), 'strlen'));
설명:
나는 사용 array_filter
이 좋지만 충분하지 않다고 생각합니다 . 왜냐하면 값은 space
and \n
, ... 배열에 보관하고 이것은 일반적으로 나쁘기 때문입니다.
내가 제안 그래서 당신은 혼합물을 사용 array_filter
하고 array_map
.
array_map
트리밍 용, array_filter
빈 값 제거 용 , 값 strlen
유지 용 0
, array_values
필요한 경우 재 인덱싱 용입니다.
시료:
$myarray = array("\r", "\n", "\r\n", "", " ", "0", "a");
// "\r", "\n", "\r\n", " ", "a"
$new1 = array_filter($myarray);
// "a"
$new2 = array_filter(array_map('trim', $myarray));
// "0", "a"
$new3 = array_filter(array_map('trim', $myarray), 'strlen');
// "0", "a" (reindex)
$new4 = array_values(array_filter(array_map('trim', $myarray), 'strlen'));
var_dump($new1, $new2, $new3, $new4);
결과 :
array(5) {
[0]=>
" string(1) "
[1]=>
string(1) "
"
[2]=>
string(2) "
"
[4]=>
string(1) " "
[6]=>
string(1) "a"
}
array(1) {
[6]=>
string(1) "a"
}
array(2) {
[5]=>
string(1) "0"
[6]=>
string(1) "a"
}
array(2) {
[0]=>
string(1) "0"
[1]=>
string(1) "a"
}
온라인 테스트 :
숫자 배열로 작업 중이고 빈 요소를 제거한 후 배열을 다시 인덱싱해야하는 경우 array_values 함수를 사용하십시오 .
array_values(array_filter($array));
참조 : PHP reindex array?
OP가 빈 문자열에 대해서만 이야기하기 때문에 가장 많이 득표 한 답변은 잘못 되었거나 적어도 완전히 사실이 아닙니다. 다음은 자세한 설명입니다.
무엇 않는 빈 평균을?
우선 우리는 공허함의 의미 에 동의해야합니다 . 다음을 필터링 하시겠습니까?
- 빈 문자열 전용 ( "")?
- 엄격하게 거짓 값? (
$element === false
) - falsey의 값? (예 : 0, 0.0, "", "0", NULL, array () ...)
- PHP의
empty()
기능 과 동일 합니까?
값을 필터링하는 방법
빈 문자열 만 필터링하려면 다음을 수행하십시오.
$filtered = array_diff($originalArray, array(""));
엄격하게 거짓 값만 필터링하려면 콜백 함수를 사용해야 합니다.
$filtered = array_diff($originalArray, 'myCallback');
function myCallback($var) {
return $var === false;
}
콜백은 일부를 제외하고 "거짓"값을 필터링하려는 모든 조합에도 유용합니다. (예 : 모든 null
및 false
등을 필터링하고 0
) :
$filtered = array_filter($originalArray, 'myCallback');
function myCallback($var) {
return ($var === 0 || $var === '0');
}
세 번째와 네 번째 경우는 (드디어 우리의 목적을 위해) 동등하며,이를 위해 사용해야하는 모든 것이 기본값입니다.
$filtered = array_filter($originalArray);
(문자열) 0의 배열 값을 유지하기 위해이 작업을 수행해야했습니다.
$url = array_filter($data, function ($value) {
return (!empty($value) || $value === 0 || $value==='0');
});
$a = array(1, '', '', '', 2, '', 3, 4);
$b = array_values(array_filter($a));
print_r($b)
다차원 배열의 경우
$data = array_map('array_filter', $data);
$data = array_filter($data);
$out_array = array_filter($input_array, function($item)
{
return !empty($item['key_of_array_to_check_whether_it_is_empty']);
}
);
function trim_array($Array)
{
foreach ($Array as $value) {
if(trim($value) === '') {
$index = array_search($value, $Array);
unset($Array[$index]);
}
}
return $Array;
}
다음 스크립트를 사용하여 배열에서 빈 요소를 제거합니다.
for ($i=0; $i<$count($Array); $i++)
{
if (empty($Array[$i])) unset($Array[$i]);
}
루프에 대한 대안을 제공하고 ... 키의 틈새를 해결하고 싶습니다 ...
제 경우에는 작업이 완료되었을 때 순차적 인 배열 키를 유지하고 싶었습니다 (내가 쳐다보고 있던 홀수뿐 아니라 홀수 키만 찾도록 코드를 설정하는 것은 나에게 취약하고 미래 친화적이지 않은 것 같았습니다.)
나는 다음과 같은 것을 더 찾고 있었다 : http://gotofritz.net/blog/howto/removing-empty-array-elements-php/
array_filter와 array_slice의 조합이 트릭을 수행합니다.
$example = array_filter($example); $example = array_slice($example,0);
효율성이나 벤치 마크에 대한 아이디어는 없지만 작동합니다.
foreach($arr as $key => $val){
if (empty($val)) unset($arr[$key];
}
$my = ("0"=>" ","1"=>"5","2"=>"6","3"=>" ");
foreach ($my as $key => $value) {
if (is_null($value)) unset($my[$key]);
}
foreach ($my as $key => $value) {
echo $key . ':' . $value . '<br>';
}
산출
1 : 5
2 : 6
array_filter
함수를 사용 하여 빈 값을 제거하십시오.
$linksArray = array_filter($linksArray);
print_r($linksArray);
단 한 줄 : 업데이트 (@suther 덕분에) :
$array_without_empty_values = array_filter($array);
빈 배열 요소 제거
function removeEmptyElements(&$element)
{
if (is_array($element)) {
if ($key = key($element)) {
$element[$key] = array_filter($element);
}
if (count($element) != count($element, COUNT_RECURSIVE)) {
$element = array_filter(current($element), __FUNCTION__);
}
return $element;
} else {
return empty($element) ? false : $element;
}
}
$data = array(
'horarios' => array(),
'grupos' => array(
'1A' => array(
'Juan' => array(
'calificaciones' => array(
'Matematicas' => 8,
'Español' => 5,
'Ingles' => 9,
),
'asistencias' => array(
'enero' => 20,
'febrero' => 10,
'marzo' => '',
)
),
'Damian' => array(
'calificaciones' => array(
'Matematicas' => 10,
'Español' => '',
'Ingles' => 9,
),
'asistencias' => array(
'enero' => 20,
'febrero' => '',
'marzo' => 5,
)
),
),
'1B' => array(
'Mariana' => array(
'calificaciones' => array(
'Matematicas' => null,
'Español' => 7,
'Ingles' => 9,
),
'asistencias' => array(
'enero' => null,
'febrero' => 5,
'marzo' => 5,
)
),
),
)
);
$data = array_filter($data, 'removeEmptyElements');
var_dump($data);
효과가있다!
귀하의 방법에 따라 다른 배열에서 해당 요소를 포착하고 다음과 같이 사용할 수 있습니다.
foreach($linksArray as $link){
if(!empty($link)){
$new_arr[] = $link
}
}
print_r($new_arr);
이것을 시도 ** ** 예
$or = array(
'PersonalInformation.first_name' => $this->request->data['User']['first_name'],
'PersonalInformation.last_name' => $this->request->data['User']['last_name'],
'PersonalInformation.primary_phone' => $this->request->data['User']['primary_phone'],
'PersonalInformation.dob' => $this->request->data['User']['dob'],
'User.email' => $this->request->data['User']['email'],
);
$or = array_filter($or);
$condition = array(
'User.role' => array('U', 'P'),
'User.user_status' => array('active', 'lead', 'inactive'),
'OR' => $or
);
With these types of things, it's much better to be explicit about what you want and do not want.
It will help the next guy to not get caught by surprise at the behaviour of array_filter()
without a callback. For example, I ended up on this question because I forgot if array_filter()
removes NULL
or not. I wasted time when I could have just used the solution below and had my answer.
Also, the logic is language angnostic in the sense that the code can be copied into another language without having to under stand the behaviour of a php function like array_filter
when no callback is passed.
In my solution, it is clear at glance as to what is happening. Remove a conditional to keep something or add a new condition to filter additional values.
Disregard the actual use of array_filter()
since I am just passing it a custom callback - you could go ahead and extract that out to its own function if you wanted. I am just using it as sugar for a foreach
loop.
<?php
$xs = [0, 1, 2, 3, "0", "", false, null];
$xs = array_filter($xs, function($x) {
if ($x === null) { return false; }
if ($x === false) { return false; }
if ($x === "") { return false; }
if ($x === "0") { return false; }
return true;
});
$xs = array_values($xs); // reindex array
echo "<pre>";
var_export($xs);
Another benefit of this approach is that you can break apart the filtering predicates into an abstract function that filters a single value per array and build up to a composable solution.
See this example and the inline comments for the output.
<?php
/**
* @param string $valueToFilter
*
* @return \Closure A function that expects a 1d array and returns an array
* filtered of values matching $valueToFilter.
*/
function filterValue($valueToFilter)
{
return function($xs) use ($valueToFilter) {
return array_filter($xs, function($x) use ($valueToFilter) {
return $x !== $valueToFilter;
});
};
}
// partially applied functions that each expect a 1d array of values
$filterNull = filterValue(null);
$filterFalse = filterValue(false);
$filterZeroString = filterValue("0");
$filterEmptyString = filterValue("");
$xs = [0, 1, 2, 3, null, false, "0", ""];
$xs = $filterNull($xs); //=> [0, 1, 2, 3, false, "0", ""]
$xs = $filterFalse($xs); //=> [0, 1, 2, 3, "0", ""]
$xs = $filterZeroString($xs); //=> [0, 1, 2, 3, ""]
$xs = $filterEmptyString($xs); //=> [0, 1, 2, 3]
echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]
Now you can dynamically create a function called filterer()
using pipe()
that will apply these partially applied functions for you.
<?php
/**
* Supply between 1..n functions each with an arity of 1 (that is, accepts
* one and only one argument). Versions prior to php 5.6 do not have the
* variadic operator `...` and as such require the use of `func_get_args()` to
* obtain the comma-delimited list of expressions provided via the argument
* list on function call.
*
* Example - Call the function `pipe()` like:
*
* pipe ($addOne, $multiplyByTwo);
*
* @return closure
*/
function pipe()
{
$functions = func_get_args(); // an array of callable functions [$addOne, $multiplyByTwo]
return function ($initialAccumulator) use ($functions) { // return a function with an arity of 1
return array_reduce( // chain the supplied `$arg` value through each function in the list of functions
$functions, // an array of functions to reduce over the supplied `$arg` value
function ($accumulator, $currFn) { // the reducer (a reducing function)
return $currFn($accumulator);
},
$initialAccumulator
);
};
}
/**
* @param string $valueToFilter
*
* @return \Closure A function that expects a 1d array and returns an array
* filtered of values matching $valueToFilter.
*/
function filterValue($valueToFilter)
{
return function($xs) use ($valueToFilter) {
return array_filter($xs, function($x) use ($valueToFilter) {
return $x !== $valueToFilter;
});
};
}
$filterer = pipe(
filterValue(null),
filterValue(false),
filterValue("0"),
filterValue("")
);
$xs = [0, 1, 2, 3, null, false, "0", ""];
$xs = $filterer($xs);
echo "<pre>";
var_export($xs); //=> [0, 1, 2, 3]
참고URL : https://stackoverflow.com/questions/3654295/remove-empty-array-elements
'Nice programing' 카테고리의 다른 글
python setup.py 제거 (0) | 2020.09.29 |
---|---|
MySQL에서 중복 값 찾기 (0) | 2020.09.29 |
선호하는 diff 도구 / 뷰어로 'git diff'출력을 보려면 어떻게해야합니까? (0) | 2020.09.29 |
malloc과 calloc의 차이점은 무엇입니까? (0) | 2020.09.29 |
Objective-C에서 난수 생성 (0) | 2020.09.29 |