gpt4 book ai didi

php - 根据公共(public)字符串对数组项进行分组

转载 作者:可可西里 更新时间:2023-10-31 23:22:50 25 4
gpt4 key购买 nike

我有以下代码,它获取两个单独的数组,翻转姓氏和名字(也删除逗号)并输出:

Director: Bert & Bertie

Writer: Bert & Bertie

Producer: Louise Knight

Producer: Miles Wilkes

Producer: Andy Welch

Actor: Craig Parkinson

Actor: Camilla Rutherford

Actor: Paul Bhattarcharjee

Actor: Ford Kieman

Actor: Maurren the Pug

Actor: Hannah Walters

DP: Lynda Hall

Cut: Matt Chodan

我需要做的是将类似的组分组以输出如下内容:

Director: Bert & Bertie

Writer: Bert & Bertie

Producer: Louise Knight, Miles Wilkes, Andy Welch

Actors: Craig Parkinson, Camilla Rutherford, Paul Bhattarcharjee, Ford Kieman, Maurren the Pug, Hannah Walters

DP: Lynda Hall

Cut: Matt Chodan

当前的 PHP 代码:

<?php 
$arrayname=explode(":::",$dwzXmlRec_1->GetFieldValue("PERSON_NAME"));
$arraynamel=count($arrayname);
$arrayrole=explode(":::",$dwzXmlRec_1->GetFieldValue("PERSON_FUNCTION"));
$arrayrolel=count($arrayrole);

$name = "Lastname, Firstname";
$names = explode(", ", $name);
$name = $names[1] . " " . $names[0];

for($i=0;$i<$arrayrolel;$i++)
{
$names = explode(", ", $arrayname[$i]);
$name = $names[1] . " " . $names[0];
echo $arrayrole[$i].': '.$name.'<br />';
}
?>

更新:只有一个问题,数据是从 xml 节点设置的,因为它在数组“as”中,所以一个角色先于另一个。例如,“ Actor ”排在第一位,然后是“导演”。有什么简单的方法可以扭转它,让导演先到后 Actor ?我添加了代码来隐藏不需要的角色/人员,请参见下文:

// print out the list of people in each role
foreach($roles as $rolename => $people) {
if ($rolename!="Cut" && $rolename!="Producer" && $rolename!="DP" && $rolename!="Writer"){
if($rolename=="Actor") { $rolename="Cast";};
echo $rolename . ": " . implode(", ", $people) . "<br />";
}
}

最佳答案

我会构建一个数组,将角色名称映射到一组担任该角色的人员。可能是这样的:

$roles = array();
for($i = 0; $i < $arrayrole1; $i++) {
$names = explode(", ", $arrayname[$i]);
$name = $names[1] . " " . $names[0];
// append the name to the array of people filling the role
$roles[$arrayrole[$i]][] = $name;
}

// print out the list of people in each role
foreach($roles as $rolename => $people) {
echo $rolename . ": " . implode(", ", $people) . "<br />";
}

关于php - 根据公共(public)字符串对数组项进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12925911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com