将一个数组值与另一个多维数组匹配,然后从多维数组中获取值
Posted
技术标签:
【中文标题】将一个数组值与另一个多维数组匹配,然后从多维数组中获取值【英文标题】:Match an array value with another multidimensional array and then get the values from the multidimensional array 【发布时间】:2020-05-29 03:57:37 【问题描述】:我想将数组 1 的值与数组 2 key DATE
的值匹配,如果找到匹配的值,则打印 MIN_TIME
的值
数组 1:
array:13 [
0 => 2020-02-13
1 => 2020-02-12
2 => 2020-02-11
3 => 2020-02-10
4 => 2020-02-09
5 => 2020-02-08
6 => 2020-02-07
7 => 2020-02-06
8 => 2020-02-05
9 => 2020-02-04
10 => 2020-02-03
11 => 2020-02-02
12 => 2020-02-01
]
数组 2:
array:8 [▼
0 => #1192 ▼
+"USERID": "59"
+"DATE": "2020-02-13"
+"MAX_TIME": "17:11:14.0000000"
+"MIN_TIME": "10:01:55.0000000"
1 => #1194 ▼
+"USERID": "59"
+"DATE": "2020-02-12"
+"MAX_TIME": "18:12:20.0000000"
+"MIN_TIME": "14:08:25.0000000"
2 => #1195 ▼
+"USERID": "59"
+"DATE": "2020-02-11"
+"MAX_TIME": "18:22:09.0000000"
+"MIN_TIME": "15:40:56.0000000"
3 => #1196 ▼
+"USERID": "59"
+"DATE": "2020-02-10"
+"MAX_TIME": "16:47:15.0000000"
+"MIN_TIME": "14:07:19.0000000"
4 => #1197 ▼
+"USERID": "59"
+"DATE": "2020-02-07"
+"MAX_TIME": "16:29:40.0000000"
+"MIN_TIME": "08:39:38.0000000"
5 => #1198 ▶
6 => #1199 ▶
7 => #1200 ▶
]
我的预期输出是:
Date Date From DB Time
2/13/2020 2/13/2020 10:01:55 AM
2/12/2020 2/12/2020 2:08:25 PM
2/11/2020 2/11/2020 3:40:56 PM
2/10/2020 2/10/2020 2:07:19 PM
2/9/2020 Not Found
2/8/2020 Not Found
2/7/2020 2/7/2020 8:39:38 AM
我从谷歌搜索并尝试了所有解决方案但失败了,请大家帮帮我。
【问题讨论】:
【参考方案1】:在下面的代码中,我们为您显示的第一个数组元素创建了 for 循环。 然后将您的收藏与第一个 where 匹配。 打印你的桌子 文档:
https://laravel.com/docs/5.7/collections#method-first-where
$array=[
0 => 2020-02-13
1 => 2020-02-12
2 => 2020-02-11
3 => 2020-02-10
4 => 2020-02-09
5 => 2020-02-08
6 => 2020-02-07
7 => 2020-02-06
8 => 2020-02-05
9 => 2020-02-04
10 => 2020-02-03
11 => 2020-02-02
12 => 2020-02-01
];
//$dbcollection is the laravel collection which you getting from the db.
// as per your second array printed we assume it will be same.
// assign that array in $dbcollection variable.
echo "<table>";
foreach($array as $value)
echo "<tr>";
echo "<td>$value</td>";
if ($dbrow=$dbcollection->firstWhere('DATE',$value))
echo "<td>$dbrow->DATE</td><td>$dbrow->MIN_TIME</td>";
else
echo "<td colspan='2'>Not Found</td>";
echo "</tr>";
echo "</table>";
希望这对你有用。
【讨论】:
【参考方案2】:您可以使用Laravel Collections 来实现:
$result = collect($array1)
->mapWithKeys(function ($item)
return [$item => null];
)
->merge(
collect($array2)->pluck('MIN_TIME', 'DATE')
)
->toArray();
/* Output:
[
2020-02-13 => 10:01:55.0000000
2020-02-12 => 14:08:25.0000000
2020-02-11 => 15:40:56.0000000
2020-02-10 => 14:07:19.0000000
2020-02-09 => null
2020-02-08 => null
2020-02-07 => 08:39:38.0000000
]
*/
您可以使用map
或transform
来获得您预期的结果:
$result = collect($array1)
->mapWithKeys(function ($item)
return [$item => null];
)
->merge(
collect($array2)->pluck('MIN_TIME', 'DATE')
)
->map(function ($item, $key)
return [
'Date' => $key,
'Time' => $item
];
)
->toArray();
【讨论】:
以上是关于将一个数组值与另一个多维数组匹配,然后从多维数组中获取值的主要内容,如果未能解决你的问题,请参考以下文章