I have a php array which contains sometimes same values (in my example film 1 and film 2) and i would like to sort the result in order to keep only one time film 1 or film 2.
PHP array : $actors
Array
(
[0] => Array
(
[0] => film 1
[1] => actor A
)
[1] => Array
(
[0] => film 1
[1] => actor B
)
[2] => Array
(
[0] => film 2
[1] => actor C
)
[3] => Array
(
[0] => film 2
[1] => actor D
)
)
I can output the datas in a foreach loop :
$i = 0;
foreach ($films as $film):
echo $film[$i][0].'<br />';
echo $film[$i][1];
$i ++;
endforeach;
And i get a result like this :
film1 actor A film1 actor B film2 actor C film2 actor D
But i would like to have a result like this :
film 1
actor A
actor B
film 2
actor C
actor E
What i've done :
I made an array with films : $films
Array
(
[0] => stdClass Object
(
[name] => film1
)
[1] => stdClass Object
(
[name] => film2
)
And i check if datas in $films
array exist in actors
array :
$i = 0;
foreach ($films as $film):
foreach ($actors as $actor):
if ($film->name == $actor[$i][0]) {
echo $actor[$i][1].'<br />';
}
endforeach;
$i ++;
endforeach;
So this code works for me but is there a better solution ? In my solution, i have a foreach loop inside a foreach loop and it could consume a lot of ressources.
For what you're looking to do, there's not a lot you can do to avoid the looping, but you could structure your array a little bit to make it do what you want. Instead of having two separate arrays of $films
and $actors
, you would want to create one array of $films
and each $actors
array is associated with the film:
$films = []; // PHP 5.4 style array shortcut. Creates a new empty array (same as array())
foreach($actors as $actor)
{
$filmName = $actor[0];
$actorName = $actor[1];
// If this film isn't in the array yet, let's create it
if(!isset($films[$filmName]))
{
$films[$filmName] = [];
}
// Add the actor to the film array
array_push($films[$filmName], $actorName);
}
Running the above code on your $actors
array results in the following $films
array
Array
(
[film 1] => Array
(
[0] => actor A
[1] => actor B
)
[film 2] => Array
(
[0] => actor C
[1] => actor D
)
)
To gain access to the list of actors in a film, you can just use $films["film 1"]
and it'll give you the array of actors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.