I am trying to search for qualifying entries in a multidimensional array and return one or more data sets as flattened, associative subarrays.
Sample input:
[
[
'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',
]
]
]
]
I want to search on the patheMovie
values (like 'The Shining') and get the parent array's name
plus only the matchedMovie
array with the matched patheMovie
value.
My code:
$search = 'Texas Chainsaw 3D';
$sorted = false;
foreach ($sorted as $n => $c)
if (in_array($search, $c)) {
$cluster = $n;
break;
}
If I search for The Shining
, the result should be:
array (
0 =>
array (
'name' => 'Jim Scott',
'nameMovie' => 'Shooter',
'genre' => 'Action, Thriller',
'patheMovie' => 'The Shining',
'patheMovieGenre' => 'Horror, Suspense/Thriller',
'score' => '52.38',
),
)
If I search for Texas Chainsaw 3D
, then the result should be:
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',
),
)
This solution will depend into two conjugated loops.
<?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;
}
?>