[英]How to sort and group datas in a php array where some datas are repeated?
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数组,其中有时包含相同的值(在我的示例电影1和电影2中),我想对结果进行排序,以便仅保留一次电影1或电影2。
PHP array : $actors
PHP数组: $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 : 我可以在foreach循环中输出数据:
$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
我用电影拍了个电影: $films
Array
(
[0] => stdClass Object
(
[name] => film1
)
[1] => stdClass Object
(
[name] => film2
)
And i check if datas in $films
array exist in actors
array : 而且我检查actors
数组中是否存在$films
数组中的数据:
$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. 在我的解决方案中,我在一个foreach循环中有一个foreach循环,它可能会消耗很多资源。
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
和$actors
数组, $films
创建一个$films
数组,每个$actors
数组都与该影片相关联:
$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 在$actors
数组上运行上面的代码将导致以下$films
数组
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. 要访问电影中的演员列表,您只需使用$films["film 1"]
,它将为您提供一系列演员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.