简体   繁体   English

将数组键转换为格式化的类名

[英]Convert array keys to formatted class names

I need to take this array and convert only the keys into one string. 我需要获取此数组并仅将转换为一个字符串。 Looking for an efficient way to do this. 寻找一种有效的方法来做到这一点。

  1. Each element having a period added before the name ( .first_post ) 在名称之前添加了句点的每个元素(.first_post)
  2. Concatenated with another string and space before each class name ( .navigation .first_post ) 在每个类名之前与另一个字符串和空格连接(.navigation .first_post)
  3. A comma after the name ( .navigation .first_post, ) 名称后面的逗号(.navigation .first_post,)
  4. Replace the "_" to "-" ( .navigation .first-post, ) “_”替换为“ - ” (.navigation .first-post,)

Items 项目

array (
  'first_post' => 'First Post' 
  'first_page' => 'First Page' 
  'prev_page' => 'Previous Page'
  'next_page' => 'Next Page'
  'last_page' => 'Last Page'
  'last_post' => 'Last Post'
);

This is what I am hoping for 这就是我所希望的

.navigation .first-post, .navigation .first-page, .navigation .prev-post,
.navigation .next-page, .navigation .last-page, .navigation .last-post

array_map gives you an elegant way of applying a transformation to each of an array's elements. array_map为您提供了一种将变换应用于每个数组元素的优雅方法。 After doing that, all you need to do is implode the result to concatenate all the values: 这样做之后,你需要做的是implode的结果来连接所有的值:

$arr = array (
  'first_post' => 'First Post',
  'first_page' => 'First Page',
  'prev_page' => 'Previous Page',
  'next_page' => 'Next Page',
  'last_page' => 'Last Page',
  'last_post' => 'Last Post'
);

function transform($x) {
    return '.navigation .' . str_replace('_', '-', $x);
};

$result = implode(', ', array_map('transform', array_keys($arr)));

Try to replace/add key with new values 尝试使用新值替换/添加键

foreach($arr as $k=>$v){
    $k = '.navigation .'.str_replace('_', '-', $k);
    $newarr[$k] = $v;
}
print_r($newarr);

if you want keys as comma separated string 如果你想要键作为逗号分隔字符串

$str = implode(", ", array_keys($newarr))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM