我正在尝试在多维数组中搜索符合条件的条目,并以扁平关联子数组的形式返回一个或多个数据集。
输入示例:
[
[
'name' => 'Dick Jansen',
'matchedMovie' => [
[
'nameMovie' => 'Saw',
'genre' => 'Horror',
'patheMovie' => 'Texas Chainsaw 3D',
'patheMovieGenre' => 'Horror',
'score' => '100.00',
]
]
],
[
'name' => 'Jim Scott',
'matchedMovie' => [
[
'nameMovie' => 'Shooter',
'genre' => 'Action, Thriller',
'patheMovie' => 'The Shining',
'patheMovieGenre' => 'Horror, Suspense/Thriller',
'score' => '52.38',
],
[
'nameMovie' => 'Resident Evil Movie',
'genre' => 'Action/Horror',
'patheMovie' => 'Texas Chainsaw 3D',
'patheMovieGenre' => 'Horror',
'score' => '63.16',
]
]
]
]
我想搜索
patheMovie
值(如“闪灵”)并获取父数组的 name
加上仅具有匹配 matchedMovie
值的 patheMovie
数组。
我的代码:
$search = 'Texas Chainsaw 3D';
$sorted = false;
foreach ($sorted as $n => $c)
if (in_array($search, $c)) {
$cluster = $n;
break;
}
如果我搜索
The Shining
,结果应该是:
array (
0 =>
array (
'name' => 'Jim Scott',
'nameMovie' => 'Shooter',
'genre' => 'Action, Thriller',
'patheMovie' => 'The Shining',
'patheMovieGenre' => 'Horror, Suspense/Thriller',
'score' => '52.38',
),
)
如果我搜索
Texas Chainsaw 3D
,那么结果应该是:
array (
0 =>
array (
'name' => 'Dick Jansen',
'nameMovie' => 'Saw',
'genre' => 'Horror',
'patheMovie' => 'Texas Chainsaw 3D',
'patheMovieGenre' => 'Horror',
'score' => '100.00',
),
1 =>
array (
'name' => 'Jim Scott',
'nameMovie' => 'Resident Evil Movie',
'genre' => 'Action/Horror',
'patheMovie' => 'Texas Chainsaw 3D',
'patheMovieGenre' => 'Horror',
'score' => '63.16',
),
)
该解决方案将取决于两个共轭环。
<?php
function searchIt($arr, $searchItem){
$result = array();
$resultIndex = 0;
for ($i =0; $i < count($arr); $i++){
for ($j = 0; $j < count($arr[$i]['matchedMovie']); $j++){
if ($arr[$i]['matchedMovie'][$j]['patheMovie'] == $searchItem){
$result[$resultIndex]['name'] = $arr[$i]['name'];
foreach ($arr[$i]['matchedMovie'][$j] as $key => $value){
$result[$resultIndex][$key] = $value;
}
$resultIndex++;
}
}
}
return $result;
}
?>
还没有测试过这个,但这应该有效:
function findYourGuy($array, $searchTerm) {
$searchTerm = 'The Shining'; // testing purpose only
foreach($array as $personArray) {
$matchedMovies = $personArray['matchedMovie'];
$name = $personArray['name'];
foreach($matchedMovies as $matchedMovie) {
if($matchedMovie['patheMovie'] == $searchTerm) {
return array('name' => $name, 'matchedMovie' => $matchedMovie)
}
}
}
return false; //no result
}
我会使用array_filter。类似的东西
$movieName = 'The shining';
$result = array_filter($movies, filterCallback);
function filterCallback($var)
{
foreach($var['matchedMovie'] as $movie) {
if($movie['PatheMovie'] == $movieName) {
return true;
}
}
}
因为此任务不仅需要过滤输入数组数据,还需要重组(展平)符合条件的行,因此您不能简单地使用
array_filter()
或 array_map()
作为一次性解决方案。因此,只需使用经典循环,然后在数据集合格的情况下推送扁平化的数据。
我将在外循环的签名中使用“数组解构”来享受方便的变量。
代码:(演示)
$result = [];
foreach ($movies as ['name' => $name, 'matchedMovie' => $matches]) {
foreach ($matches as $entry) {
if ($movieName === $entry['patheMovie']) {
$result[] = ['name' => $name] + $entry;
}
}
}
var_export($result)