提取值为空的键/值对
提取值为空的键/值对
我有一个使用案例,需要创建一个包含原始数组中值为空的键/值对的数组。
这个示例数据是实际数据的简化表示。下面的代码产生了期望的结果,但是否有更简洁的方法来编写它?是否有一种比下面的代码更短的不使用foreach
的替代方法?
$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58]; $result = []; foreach ($data as $key => $value) { if (empty($value)) $result[$key] = $value; } echo print_r($result, 1);
期望结果:
问题的原因是需要从给定的数组中提取值为空的键值对。解决方法是使用PHP的array_filter()函数来过滤数组,并使用empty()函数判断值是否为空。如果值为空,则将其保留下来。具体代码如下:
$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58]; $result = array_filter($data, fn($e) => empty($e)); print_r($result);
输出结果为:
Array ( [peas] => [turnips] => )
在PHP 7.4之前,可以使用匿名函数来实现相同的功能:
$data = ['beans' => 23, 'peas' => null, 'carrots' => 17, 'turnips' => '', 'potatoes' => 58]; $result = array_filter($data, function($e) { return empty($e); }); print_r($result);
以上是解决问题的示例代码和输出结果。你可以在这里查看PHP 7.4的演示:https://3v4l.org/hgZg8