如何将字符串中的数组转换为与第一个数组字串联的字符串,如array[0].'->'. array[1]

pkwftd7m  于 2022-10-30  发布在  PHP
关注(0)|答案(3)|浏览(155)
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];

这是一个数组,我想把它转换成如下的字符串,字符串应该是一个,它只是一个字符串。
第一个

pvcm50d1

pvcm50d11#

在迭代由箭头分隔的字符串数组时,分解箭头上的每个元素,将第一个值与其余元素分离,然后迭代分解中的其余元素,并将缓存的第一个值置于前面,然后将其推入结果数组。
代码:(Demo

$result = [];
foreach ($arr as $string) {
    $parts = explode('->', $string);
    $parent = array_shift($parts);
    foreach ($parts as $child) {
        $result[] = "{$parent}->$child";
    }
}
var_export($result);
xqkwcwgp

xqkwcwgp2#

这里的解决方案:

<?php
//This might help full
$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];

$result="";
$newline="<br>";
foreach($arr as $data){
    $wordlist=explode('->',$data);
    $firstword=$wordlist[0];
    $temp='';
    foreach($wordlist  as $key=>$value){
      if($key > 0){
        $temp.=$firstword."->".$value.$newline;
      }
    }
    $temp.=$newline;
    $result.=$temp;
}
echo $result;
?>

Output :

Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts

Users->User Departments
Users->Department Hierarchy

Settings->Registrar
Settings->Finance

Logs->Second Opinion Log
bvjxkvbb

bvjxkvbb3#

$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];

foreach ($arr as $path) {
  $path_elements = explode('->', $path);
  if (count($path_elements) > 1) {
    $path_head = $path_elements[0];
    $path_tail = array_slice($path_elements, 1);
    foreach ($path_tail as $path_item) {
      echo $path_head, '->', $path_item, "<br>";
    }
    echo "<br>";  
  }
}

演示:https://onlinephp.io/c/9eb2d
或者,使用JOIN()

$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
        'Users->User Departments->Department Hierarchy',
        'Settings->Registrar->Finance',
        'Logs->Second Opinion Log'];

foreach ($arr as $path) {
  $path_elements = explode('->', $path);
  if (count($path_elements) > 1) {
    $path_head = $path_elements[0];
    $path_tail = array_slice($path_elements, 1);
    echo
      $path_head,
      '->',
      join('<br>'. $path_head.'->',$path_tail),
      '<br><br>';
  }
}

演示:https://onlinephp.io/c/c1826

相关问题