加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 基于公共字符串对数组项进行分组

发布时间:2020-12-13 16:47:52 所属栏目:PHP教程 来源:网络整理
导读:我有以下代码,它抓取两个单独的数组,翻转姓氏和名字(也删除逗号)并输出: Director: Bert Bertie Writer: Bert Bertie Producer: Louise Knight Producer: Miles Wilkes Producer: Andy Welch Actor: Craig Parkinson Actor: Camilla Rutherford Actor: Paul
我有以下代码,它抓取两个单独的数组,翻转姓氏和名字(也删除逗号)并输出:

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’首先出现,然后是’Director’.有没有任何简单的方法来反转它,所以Director先来然后Cast?我添加了代码来隐藏不需要的角色/人员,如下所示:

// 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 />";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读