我有一个多维数组,如下所示:
<% if @user.items.offset(0).last.issue_date + 2.years > Date.today %>
任何关于什么是最快和最有效的方法只返回非空PHONE值的数组的想法,即我希望得到的数组是:
$array = [
0 => [
"id" => 1,
"name" => "Sammy",
"phone" => "2348055643322",
"email" => "sammy@abc.com"
],
1 => [
"id" => 2,
"name" => "Saheed",
"phone" => "",
"email" => "saay@aol.com"
],
2 => [
"id" => 3,
"name" => "Edwin",
"phone" => "2348099993322",
"email" => "eddy@gmail.com"
],
3 => [
"id" => 3,
"name" => "Jonadab",
"phone" => "2348066773322",
"email" => "jonadab@gmail.com"
],
4 => [
"id" => 3,
"name" => "Mercy",
"phone" => "",
"email" => "mercy@sysnet.com"
]
];
答案 0 :(得分:1)
您可以使用array_filter
$array = //Your array
$column = 'phone'; //column to filter
$result = array_filter($array, function($o) use($column) {
return trim( $o[$column] ) !== '' && $o[$column] !== null;
});
print_r( $result );
这将导致:
Array
(
[0] => Array
(
[id] => 1
[name] => Sammy
[phone] => 2348055643322
[email] => sammy@abc.com
)
[2] => Array
(
[id] => 3
[name] => Edwin
[phone] => 2348099993322
[email] => eddy@gmail.com
)
[3] => Array
(
[id] => 3
[name] => Jonadab
[phone] => 2348066773322
[email] => jonadab@gmail.com
)
)
Doc:array_filter()
答案 1 :(得分:1)
这对我有用:
$resulting_array = array_filter($array, function ($entry) {
return !empty($entry['phone']);
});
答案 2 :(得分:0)
简单的方法,我认为最快的方式:
$response = [];
foreach ($array as $index => $row) {
if (strlen($row['phone'])) {
// keep the original index
$response [$index]= $row;
}
}
var_dump($response);
答案 3 :(得分:0)
另一种选择是使用array_column,array_filter和array_intersect_key。
Array_column和array_filter过滤掉非空的电话列 Array_intersect_key将从$ phone获取密钥并匹配$ array。
$phone = array_filter(array_column($array, "phone"));
$filtered = array_intersect_key($array, $phone);
Var_dump($filtered);
由于问题是“最快的方法”,请参见此处:https://3v4l.org/nafbq