$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];这是数组,我想把它转换成字符串,就像下面那样,字符串应该是一个,它只是在一个字符串中连接。
Governance->Policies
Governance->Prescriptions
Governance->CAS Alerts
Users->User Departments
Users->Department Hierarchy
Settings->Registrar
Settings->Finance
Logs->Second Opinion Log$arr = ['Governance->Policies->Prescriptions->CAS Alerts',
'Users->User Departments->Department Hierarchy',
'Settings->Registrar->Finance',
'Logs->Second Opinion Log'];
$temp = '';
for($i = 0; $i < count($arr); $i++){
$arrVal = [];
$arrVal = explode('->',$arr[$i]);
if(count($arrVal) > 1){
for($j=0; $j < count($arrVal); $j++){
if($j == 0){
$temp .= $arrVal[$j];
}else{
$temp .='->'.$arrVal[$j]."\n";
if($j == count($arrVal) - 1){
$temp .= "\n";
}else{
$temp .= substr($temp, 0, strpos($temp, "->"));
}
}
}
}
}
echo $temp;发布于 2022-10-28 07:52:56
在这里,解决方案:
<?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发布于 2022-10-29 14:06:48
当您迭代由箭头分隔的字符串数组时,爆炸其箭头上的每个元素,将第一个值从其余的元素中分离出来,然后从爆炸中迭代其余的元素,并将缓存的、第一个值和推入结果数组。
代码:(演示)
$result = [];
foreach ($arr as $string) {
$parts = explode('->', $string);
$parent = array_shift($parts);
foreach ($parts as $child) {
$result[] = "{$parent}->$child";
}
}
var_export($result);发布于 2022-10-28 08:05:00
$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://stackoverflow.com/questions/74231774
复制相似问题