I have to find where a given string is in my multidimensional array. So this is my array
$input = array(array('time' => '18:31:00', 'artist' => 'LUIS RODRIGUEZ & DEN HARROW'), array('time' => '18:32:00', 'artist' => 'J BALVIN'), array('time' => '18:33:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'), array('time' => '18:34:00', 'artist' => 'THE BLACK EYED PEAS FT J BALVIN'), array('time' => '18:35:00', 'artist' => 'J BALVIN'));
I have to find at what time I can find this
$artista_inserito = 'THE BLACK EYED PEAS FT J BALVIN';
So I use a function to delimiter my array and even string
function multiexplode($delimiters, $string)
{
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
// array with string delimeter
$array_delimiter_artisti = array(' FEAT ', ' feat ', ' FT ', ' ft ', ' + ', ' AND ', ' and ', ' E ', ' e ', ' VS ', ' vs ', ' FEAT. ', ' feat. ', ' FT. ', ' ft. ', ' VS. ', ' vs. ', ' , ', ' & ');
// I split the current artist
$artisti_inseriti = multiexplode($array_delimiter_artisti, $artista_inserito);
So I search the given string un my array
foreach ($input as $split) {
$time = $split['time'];
$artist = $split['artist'];
$lista_artisti = multiexplode($array_delimiter_artisti, $artist);
foreach ($lista_artisti as $nuovo) {
$artista_split = $nuovo;
// copy all new data in new array
$nuovo_array_dati[] = array('time' => $time, 'artist' => $artista_split);
}
}
foreach ($nuovo_array_dati as $controllo) {
$time = $controllo['time'];
$artist = $controllo['artist'];
foreach ($artisti_inseriti as $trova_artista) {
$artista_singolo = $trova_artista;
foreach ($controllo as $index => $a) {
if (strstr($a, $artista_singolo)) {
// now I can print where I found the given string $artista_inserito
echo "$artista_singolo is at $time ";
}
}
}
}
So this is my output
J BALVIN is at 18:32:00
THE BLACK EYED PEAS is at 18:33:00
J BALVIN is at 18:33:00
THE BLACK EYED PEAS is at 18:34:00
J BALVIN is at 18:34:00
J BALVIN is at 18:35:00
Can I improve this? Thanks
strstr()
to check the existence of a substring in a string -- usingstrpos()
is a better performer. I don't see any reason to check the time column's data. Why do you only use the first element of$array_delimiter_artisti
? \$\endgroup\$