PHP如何从一个数组复制到另一个限制为null或空的数组


PHP How do i copy from an array to another array restricting null or empty

所以我有一个很大的数组,有很多选项,都是针对汽车的,所以里程和声音以及这个和那个现在假设我的客户端没有提供里程,在我将这个数组发送到我的函数之前,我想确保每个元素都不是空的,那些没有被放置在新数组中的元素将被放入sql插入

这是我的阵列:

Array ( [year] => select [make] => Buick [model] => [engine] => [mileage] => [price] => [vin] => [att1] => [att2] => [att3] => [att4] => [bodystyle] => [fuel] => [hp] => [cyl] => Select [enginesize] => L [transmission] => [shifts] => [od] => [sound] => [gps] => [sound_system] => [sradio] => [tachometer] => [clock] => [trip] => [eweather] => [digitalboard] => [drive] => [fxf] => [cruisecontrol] => [tiltsteering] => [ac] => [removabletop] => [keyless] => [airbags] => [alloy] => [trunkantitrap] => [ewindows] => [emirrors] => [eseat] => [elocks] => [antitheft] => [ledheadlights] => )

那么,如果它不是空的,我怎么能循环通过它呢?把它添加到一个新的数组上,也是一个收集名称和值的关联数组

对不起,我有点困惑

您可以使用array_filter:从数组中删除空值

$arr = ['foo' => null, 'bar' => 'not null'];
$filtered = array_filter($arr); // contains just "bar" => "not null"

但是,请注意,这将删除所有与布尔值false相比较的值。在其他值中,这包括空字符串、字符串"0"和整数0。如果不想删除这些值,则必须为array_filter提供自定义回调。例如,仅删除null值:

$arr = ['foo' => null, 'bar' => '0'];
$filtered = array_filter($arr, function($o) { return $o !== null; });

像一样尝试

$new_arr = array();
foreach($my_arr as $key => $value) {
    if($value != '' && $value != NULL )
         $new_arr[$key] = $value;
}