Php - 仅当所有值都不为空时才将关联数组添加到新数组
Php - add associative array to new array only if all values aren't empty
我正在遍历 php 中的一个关联数组,并希望将该数组添加到一个新数组中,但前提是键值对中的所有值($name 或 $value)都是'空。我正在遍历的数组如下所示:
$arr = ['label' => $name, 'value' => $value]
我试过以下方法:
$arr = ['label' => $name, 'value' => $value]
$filtered = [];
foreach ($arr as $key => $val) {
if(!empty($val)) {
$customAttrsFiltered[] = [$arr];
}
}
但是没有成功。
任何帮助表示赞赏
这对你有用吗?
$arr = ['label' => $name, 'value' => $value]
$filtered = [];
$hasEmptyValue = false;
foreach ($arr as $key => $val) {
if(empty($val)) {
$hasEmptyValue = true;
}
}
if(!$hasEmptyValue) {
$customAttrsFiltered[] = [$arr];
}
试试这个
<?php
$array = [
[ 'label' => 'Label 1', 'value' => 'Value 1' ],
[ 'label' => 'Label 2', 'value' => '' ],
[ 'label' => 'Label 3', 'value' => 'Value 3' ],
[ 'label' => 'Label 4', 'value' => '' ],
];
$new_array = array_filter( array_map( function( $item ) {
if ( empty( $item['value'] ) ) {
return;
}
return $item;
}, $array ) );
print_r( $new_array );
你应该得到这样的东西
Array
(
[0] => Array
(
[label] => Label 1
[value] => Value 1
)
[2] => Array
(
[label] => Label 3
[value] => Value 3
)
)
我正在遍历 php 中的一个关联数组,并希望将该数组添加到一个新数组中,但前提是键值对中的所有值($name 或 $value)都是'空。我正在遍历的数组如下所示:
$arr = ['label' => $name, 'value' => $value]
我试过以下方法:
$arr = ['label' => $name, 'value' => $value]
$filtered = [];
foreach ($arr as $key => $val) {
if(!empty($val)) {
$customAttrsFiltered[] = [$arr];
}
}
但是没有成功。 任何帮助表示赞赏
这对你有用吗?
$arr = ['label' => $name, 'value' => $value]
$filtered = [];
$hasEmptyValue = false;
foreach ($arr as $key => $val) {
if(empty($val)) {
$hasEmptyValue = true;
}
}
if(!$hasEmptyValue) {
$customAttrsFiltered[] = [$arr];
}
试试这个
<?php
$array = [
[ 'label' => 'Label 1', 'value' => 'Value 1' ],
[ 'label' => 'Label 2', 'value' => '' ],
[ 'label' => 'Label 3', 'value' => 'Value 3' ],
[ 'label' => 'Label 4', 'value' => '' ],
];
$new_array = array_filter( array_map( function( $item ) {
if ( empty( $item['value'] ) ) {
return;
}
return $item;
}, $array ) );
print_r( $new_array );
你应该得到这样的东西
Array
(
[0] => Array
(
[label] => Label 1
[value] => Value 1
)
[2] => Array
(
[label] => Label 3
[value] => Value 3
)
)