Php 我需要忽略数组的某些项,并从剩余项创建首字母
我需要避免从数组返回的CN=Users、DC=aab、DC=local值。然后将其余名称的首字母缩写保存到新数组中。任何帮助都将不胜感激。我只是不确定从哪里开始。 这就是我现在执行以下操作时它返回的方式Php 我需要忽略数组的某些项,并从剩余项创建首字母,php,arrays,Php,Arrays,我需要避免从数组返回的CN=Users、DC=aab、DC=local值。然后将其余名称的首字母缩写保存到新数组中。任何帮助都将不胜感激。我只是不确定从哪里开始。 这就是我现在执行以下操作时它返回的方式 $reportees = $_SESSION["user"]->directreports; $reportees = implode(",", $reportees); CN=John Doe,CN=Users,DC=aab,DC=local,CN=Jane Ann Doe,CN=Us
$reportees = $_SESSION["user"]->directreports;
$reportees = implode(",", $reportees);
CN=John Doe,CN=Users,DC=aab,DC=local,CN=Jane Ann Doe,CN=Users,DC=aab,DC=local您可以使用闭包筛选数组,并让它为不需要的项返回FALSE,以便可以使用array\u filter对其进行筛选 通过这种方式,您可以增量地检查结果,我发现这更容易调试
$values = array_map(
/* Get a reportee, return the name or FALSE */
function($reportee) {
list($key, $value) = explode('=', $reportee);
switch ($key) {
case 'CN': // CN=Users or CN=Jane Ann Doe
if ('Users' === $value) {
return false;
}
// $value is now hopefully Jane Ann Doe.
return $value;
default: // Anything else gets FALSEd.
return false;
}
},
$reportees
);
// Eliminate unwanted results:
// [ 0 => false, 1 => false, 2 => false, 3 => 'Jane Ann Doe', 4 => false ]
$values = array_filter($values);
// $values should now be something like [ 3 => 'Jane Ann Doe' ]
// Get initials.
$values = array_map(
/* input: "Jane Ann Doe"; output: "JAD" */
function ($value) {
$words = preg_split('#\\s+#', $value);
$initials = array_map(
function ($word) {
return substr($word, 0, 1);
},
$words
);
return implode('', $initials);
},
$values
);
// $values is now [ '3' => 'JAD' ].
// You can use array_values($values) to renumber the array.
以下各项应能正常工作(PHP>=5.4):
输出将是:
string(10) "JD,B,JAD,B"
附录(仅核对首字母和末字母缩写):
输出:
array (
0 => 'J D',
1 => 'J A D',
)
array (
0 => 'JD',
1 => 'JD',
)
这一个也起作用了,我只需要把字母之间的空格去掉。谢谢。我该如何避免中间的首字母?所以它只输出第一个和最后一个name@Ryan,您正在更改摘要!添加了示例。很抱歉更改,感谢您的输入。缩写“B”来自哪里?因为帖子已经编辑,所以有一个额外的条目“DC=byl”。
string(10) "JD,B,JAD,B"
<?php
$in = ['CN=John Doe','CN=Users','DC=aab','DC=local','CN=Jane Ann Doe','CN=Users','DC=aab','DC=local'];
function initials_from_value($i) {
strtok($i, '=');
$i = strtok('=');
$names = explode(' ', $i);
$initials = array_map(function ($i) { return substr($i, 0, 1); }, $names);
return $initials;
}
$out = array();
foreach($in as $item) {
if(strpos($item, 'CN=') === 0 && $item !== 'CN=Users') {
$out[] = implode(' ', initials_from_value($item));
}
}
var_export($out);
array (
0 => 'J D',
1 => 'J A D',
)
$out = array();
foreach($in as $item) {
if(strpos($item, 'CN=') === 0 && $item !== 'CN=Users') {
if( ($initials = initials_from_value($item)) && count($initials) >= 2) {
$first = reset($initials);
$last = end($initials);
$out[] = $first . $last;
}
}
}
var_export($out);
array (
0 => 'JD',
1 => 'JD',
)