[英]PHP array_column to return with values only
Is it possible to get a result from array_column that has values only?是否可以从仅具有值的 array_column 获得结果?
sample array i want to array_column我想要的示例数组 array_column
$array = [
['name' => ''],
['name' => 'John'],
['name' => 'Doe']
]
when i use array_column this is what i get当我使用 array_column 这就是我得到的
Array
(
[0] =>
[1] => John
[2] => Doe
)
I was going to just use foreach and check each and every value but i was wondering if there is a much easier way to do this我打算只使用 foreach 并检查每个值,但我想知道是否有更简单的方法来做到这一点
thanks谢谢
I think you want something like this (to get only the columns which has a value):我认为您想要这样的东西(仅获取具有值的列):
$array = [
['name' => ''],
['name' => 'John'],
['name' => 'Doe']
];
$result = array_filter(array_column($array, 'name'));
The array_filter will filter out empty names and you'll get something like this: array_filter将过滤掉空名称,您将得到如下内容:
// print_r($result);
Array
(
[1] => John
[2] => Doe
)
Also, if you need to reorder the indices then you can use array_values like this:此外,如果您需要重新排序索引,则可以像这样使用array_values :
$result = array_filter(array_column($array, 'name'));
// If you want to reorder the indices
$result = array_values($result);
// print_r($result);
Array
(
[0] => John
[1] => Doe
)
You could also do this to remove both null and empty values:您也可以这样做来删除 null 和空值:
// PHP 7.4+
$result = array_filter(array_column($array, 'name'), fn($val) => !is_null($val) && $val !== '');
// PHP 5.3 and later
$result = array_filter(array_column($array, 'name'), function($val) { return !is_null($val) && $val !== ''; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.